快速排序算法 - Swift
func quickSortPartition(array : [Int], left : Int, right: Int, rise : Bool) ->([Int], Int){ var i = left var j = right let key = array[i] var sortArray = array while (i < j) { while (i < j && (rise ? (key <= sortArray[j]) : (key >= sortArray[j])) ) { j -= 1; } guard i < j else { continue } sortArray[i] = sortArray[j]; print(">>>\(sortArray) \(key) \(i) \(j)") while (i < j && (rise ? (key >= sortArray[i]) : (key <= sortArray[i])) ) { i += 1; } guard i < j else { continue } sortArray[j] = sortArray[i]; print("<<<\(sortArray) \(key) \(i) \(j)") } sortArray[i] = key; return (sortArray, i)}func sortByFast(array : [Int], left : Int, right: Int, rise : Bool) -> [Int]{ guard left < right else { return array } var (sortArray, p) = quickSortPartition(array: array, left: left, right: right, rise: rise) print("left_Sort \(sortArray) left :\(left) right:\(p-1)") sortArray = sortByFast(array: sortArray, left: left, right: p-1, rise: rise) print("rightSort \(sortArray) left :\(p+1) right:\(right)") sortArray = sortByFast(array: sortArray, left: p+1, right: right, rise: rise) return sortArray}
var sortByFast_list : [Int] = [86, 37, 56, 29, 92, 73, 15, 63, 30, 8];let sortByFast_list_count = sortByFast_list.countlet sortByFast_list2 = sortByFast(array: sortByFast_list, left: 0, right: sortByFast_list_count-1 , rise: true)let sortByFast_list3 = sortByFast(array: sortByFast_list, left: 0, right: sortByFast_list_count-1 , rise: false)
[8, 15, 29, 30, 37, 56, 63, 73, 86, 92][92, 86, 73, 63, 56, 37, 30, 29, 15, 8]
参考文章