[Swift 3.0] Fundamental & Algorithm

[Swift Algorithm] Selection sort

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

Swift

func selectionSort(array: inout [Int]) -> [Int] {
    guard array.count > 1 else { return array } 
    for x in 0 ..< array.count - 1 {
        var lowest = x
        for y in x + 1 ..< array.count {
            if array[y] < array[lowest] {
                lowest = y
            }
        }
        if x != lowest { swap(&array[x], &array[lowest]) }
    }
    return a
}

Objective-C

NSMutableArray* selectionSort(NSMutableArray *arr)
{
    int minIndex = 0;
    
    for (int i = 0; i < arr.count - 1; i++) {
        minIndex = i;
        
        for (int j = i + 1; j < arr.count; j++) {
            if ([arr objectAtIndex:j] < [arr objectAtIndex:minIndex]) {
                minIndex = j;
            }
        }
        
        if (minIndex != i) {
            [arr exchangeObjectAtIndex:i withObjectAtIndex:minIndex];
        }
    }
    return arr;
}
上一篇下一篇

猜你喜欢

热点阅读