快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:經過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的全部數據都比另一部分的全部數據都要小,而後再按此方法對這兩部分數據分別進行快速排序,整個排序過程能夠遞歸進行,以此達到整個數據變成有序序列。bash
func QuickSort<T: Comparable>(dest:[T])->[T]{
guard dest.count > 1 else {
return dest
}
let middle = dest[dest.count/2]
let bigger = dest.filter { (t:T) -> Bool in
return t > middle
}
let equal = dest.filter { (t:T) -> Bool in
return t == middle
}
let less = dest.filter { (t:T) -> Bool in
return t < middle
}
let finally = QuickSort(dest: less) + equal + QuickSort(dest: bigger)
return finally
}
複製代碼
測試用例less
var test1 = [1,2,-1,34,3434,3434,3,2,4,3,243,23,34,3434,32,-2,0,0,343443,54,25]
print(QuickSort(dest: test1))
複製代碼
結果 測試