Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 21, 2019 18:24
Show Gist options
  • Select an option

  • Save davidinga/b400d836ebcb6a17058d6a45b29c0f34 to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/b400d836ebcb6a17058d6a45b29c0f34 to your computer and use it in GitHub Desktop.
Recursive QuickSort implementation that extends Array. Pivot set to the last element in the partition.
extension Array where Element: Comparable {
private func partition(array: inout [Element], low: Int, high: Int) -> Int {
let pivot = array[high]
var i = low - 1
for j in low..<high {
if array[j] <= pivot {
i += 1
array.swapAt(i, j)
}
}
array.swapAt(i + 1, high)
return i + 1
}
mutating func quickSort(low: Int = 0, high: Int? = nil) {
let high = high ?? self.count - 1
if low < high {
let pi = partition(array: &self, low: low, high: high)
quickSort(low: low, high: pi - 1)
quickSort(low: pi + 1, high: high)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment