Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created December 9, 2016 02:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/5e55907cf05acdb39eb49e6d8b591c02 to your computer and use it in GitHub Desktop.
Save khanlou/5e55907cf05acdb39eb49e6d8b591c02 to your computer and use it in GitHub Desktop.
Quicksort - the only use for partition(by:) I could find
import Foundation
extension Array where Element: Comparable {
mutating func quickSort() {
self[self.indices].quickSort()
}
}
extension ArraySlice where Element: Comparable {
mutating func quickSort() {
guard self.count > 1 else { return }
let pivotValue = self[startIndex]
let pivotIndex = self.partition(by: { $0 >= pivotValue })
if (pivotIndex == startIndex) {
self[index(after: startIndex)..<self.endIndex].quickSort()
} else {
self[self.startIndex..<pivotIndex].quickSort()
self[pivotIndex..<self.endIndex].quickSort()
}
}
}
for _ in 0..<100 {
var a = (0..<10).map({ _ in arc4random_uniform(100) })
var copy = a
a.quickSort()
if a != copy.sorted() {
print("failed!")
print(a)
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment