iOS数组从小到大排序算法

2022-02-08  本文已影响0人  要上天的程序员

publicfuncselectionSort(_array: [T],_isOrderedBefore: (T, T) ->Bool) -> [T] {

    guard array.count > 1 else {return array }

    var a  =  array

    for x in 0..< a.count-1{

        // Find the lowest value in the rest of the array.

        var lowest = x

        for y in x +1 ..<  a.count{

            if isOrderedBefore(a[y], a[lowest]) {

                lowest = y

            }

        }

        // Swap the lowest value with the current array index.

        if x != lowest {

            a.swapAt(x, lowest)

        }

    }

    return a

}

XTest->:


letlist= [10, -1,3,9,2,27,8,5,1,3,0,26]

selectionSort(list)

selectionSort(list, <)

selectionSort(list, >)

PS:

sort 函式只有一個參數,但這個參數比較特別,它是 Closure,在Closure 內執行的結果必須回傳 Bool 值,isOrderedBefore 表示如果回傳為 true,將排在前面,反之往後排序。

上一篇 下一篇

猜你喜欢

热点阅读