Created
August 21, 2019 18:24
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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