Skip to content

Instantly share code, notes, and snippets.

@therealbnut
Last active June 28, 2016 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therealbnut/391b59b347ef6f0e0e42cb2c9731873c to your computer and use it in GitHub Desktop.
Save therealbnut/391b59b347ef6f0e0e42cb2c9731873c to your computer and use it in GitHub Desktop.
// 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