[Swift Algorithm] Insertion sort

Swift

func insertionSort(inout array: [Int]) {
    var a = array                             // 1
    for x in 1.. 0 && a[y] < a[y - 1] {        // 3
            swap(&a[y - 1], &a[y])
            y -= 1
        }
    }
}

Objective-C

NSMutableArray* insertionSort(NSMutableArray *arr)
{
    for (int i = 1; i < arr.count; i++) {
        int j = i;
        while (j > 0 && [[arr objectAtIndex:j] integerValue ] < [[arr objectAtIndex:j - 1] integerValue]) {
            [arr exchangeObjectAtIndex:j withObjectAtIndex:j - 1];
            j--;
        }
    }
    return arr;
}

你可能感兴趣的:([Swift Algorithm] Insertion sort)