daniel.baird
10/4/2018 - 4:32 AM

Insertion Sort

Basic insertion sort implementation in Objective-c. Not actually tested.

// Insertion Sort
- (NSArray<NSNumber *> *)insertionSort:(NSArray<NSNumber *> *)unsortedArray {
    NSMutableArray<NSNumber *> *array = [unsortedArray mutableCopy];
    NSInteger count = array.count;
    NSInteger j;
    
    // Start with i at the second index, and continue through till the length of the array.
    for (NSInteger i = 1; i < count; i++) {
        j = i;
        // While j > 0 keep us from going back past the end index.
        // We are going to contine swapping values as long as j - 1 > j.
        while(j > 0 && [array[j-1] intValue] > [array[j] intValue]) {
            // Swap the objects
            [array exchangeObjectAtIndex:j withObjectAtIndex:(j-1)];

            // Move j back 1 so that we can continue to float this down to where it needs to be.
            j--;
        }
    }
    
    return array;
}