Chapter 35: Quicksort Challenges
public func quicksortIterativeLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) {
var stack = Stack<Int>()
stack.push(low)
stack.push(high)
// iteratively
while !stack.isEmpty {
guard let end = stack.pop(), let start = stack.pop() else {
continue
}
// 進行 Lomuto’s partition strategy.
let p = partitionLomuto(&a, low: start, high: end)
// 表示pivot-1跟start之間還可以切割
if p - 1 > start {
stack.push(start)
stack.push(p - 1)
}
// 表示pivot+1跟end之間還可以切割
if p + 1 < end {
stack.push(p + 1)
stack.push(end)
}
}
}Last updated