Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active June 28, 2016 17:04
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 oisdk/7ecc162bf65245cdc3612d9874439c70 to your computer and use it in GitHub Desktop.
Save oisdk/7ecc162bf65245cdc3612d9874439c70 to your computer and use it in GitHub Desktop.
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