Last active
June 28, 2016 23:48
-
-
Save therealbnut/391b59b347ef6f0e0e42cb2c9731873c to your computer and use it in GitHub Desktop.
This file contains 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
// Using XCode 7.3.1 (it's all I had at the time) | |
extension MutableCollectionType where Generator.Element == SubSequence.Generator.Element { | |
mutating func selectionSort(isOrderedBefore compare: (Generator.Element, Generator.Element) throws -> Bool) rethrows { | |
for currentIndex in self.startIndex ..< self.endIndex { | |
// (index,element) pairs after the current index | |
let pairs = zip(currentIndex ..< self.endIndex, self.suffixFrom(currentIndex)).lazy | |
// the pair with the minimum element | |
let pair = try pairs.minElement({ try compare($0.1, $1.1) }) | |
// swap the pair, should never be nil but checking anyway | |
if let (minIndex, minElement) = pair { | |
self[minIndex] = self[currentIndex] | |
self[currentIndex] = minElement | |
} | |
} | |
} | |
} | |
extension MutableCollectionType where Generator.Element == SubSequence.Generator.Element, Generator.Element: Comparable { | |
mutating func selectionSort() { | |
return self.selectionSort(isOrderedBefore: <) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment