[Swift 3.0] Fundamental & Algorithm

[Swift Algorithm] Insertion sort

2016-07-16  本文已影响22人  sunlitamo

Swift

func insertionSort(inout array: [Int]) {
    var a = array                             // 1
    for x in 1..<a.count {                    // 2
        var y = x
        while y > 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;
}
上一篇下一篇

猜你喜欢

热点阅读