Created
December 9, 2016 02:43
-
-
Save khanlou/5e55907cf05acdb39eb49e6d8b591c02 to your computer and use it in GitHub Desktop.
Quicksort - the only use for partition(by:) I could find
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
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