Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active Jun 28, 2016
Embed
What would you like to do?
extension MutableCollection where
SubSequence: MutableCollection,
SubSequence.Iterator.Element == Iterator.Element,
SubSequence.SubSequence == SubSequence,
Indices.Iterator.Element == Index,
SubSequence.Indices.Iterator.Element == SubSequence.Index,
Iterator.Element: Comparable {
mutating func selectionSort() {
if let minInd = indices.min(isOrderedBefore: { (i,j) in self[i] < self[j] }) {
if minInd != startIndex { swap(&self[startIndex],&self[minInd]) }
self[index(after: startIndex)..<endIndex].selectionSort()
}
}
func selectionSorted() -> Self {
var copy = self
copy.selectionSort()
return copy
}
}
extension MutableCollection where
SubSequence: MutableCollection,
SubSequence.Iterator.Element == Iterator.Element,
SubSequence.SubSequence == SubSequence,
Indices.Iterator.Element == Index,
SubSequence.Indices.Iterator.Element == SubSequence.Index {
mutating func selectionSort(isOrderedBefore cmp: (Iterator.Element, Iterator.Element) -> Bool) {
if let minInd = indices.min(isOrderedBefore: { (i,j) in cmp(self[i],self[j]) }) {
if minInd != startIndex { swap(&self[startIndex],&self[minInd]) }
self[index(after: startIndex)..<endIndex]
.selectionSort(isOrderedBefore: cmp)
}
}
func selectionSorted(isOrderedBefore cmp: (Iterator.Element, Iterator.Element) -> Bool) -> Self {
var copy = self
copy.selectionSort(isOrderedBefore: cmp)
return copy
}
}
extension MutableCollection where
SubSequence: MutableCollection,
SubSequence.Iterator.Element == Iterator.Element,
SubSequence.SubSequence == SubSequence,
Indices.Iterator.Element == Index,
SubSequence.Indices.Iterator.Element == SubSequence.Index,
Iterator.Element: Comparable {
mutating func selectionSort() {
selectionSort(isOrderedBefore: <)
}
func selectionSorted() -> Self {
return selectionSorted(isOrderedBefore: <)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment