快速排序是很常见的算法, 那么Swift要如何实现呢? 下面提供了一种思路
func quickSortWithArray<T:Comparable>(array: [T]) -> [T] {
if array.count == 0 || array.count == 1 {
return array
}
let baseIndex = Int(arc4random()) % array.count
let baseNumber = array[baseIndex]
var unsortedArray = Array(array)
unsortedArray.remove(at: baseIndex)
var leftArray = [T]()
var rightArray = [T]()
for curNumber in unsortedArray {
if (curNumber < baseNumber) {
leftArray.append(curNumber)
} else {
rightArray.append(curNumber)
}
}
var sortedArray = [T]()
for num in quickSortWithArray(array: leftArray) {
sortedArray.append(num)
}
sortedArray.append(baseNumber)
for curNumber in quickSortWithArray(array: Array(rightArray)) {
sortedArray.append(curNumber)
}
return sortedArray
}