Skip to content

Instantly share code, notes, and snippets.

@proxpero
Last active January 27, 2016 18:35
Show Gist options
  • Save proxpero/621366da831116744e5b to your computer and use it in GitHub Desktop.
Save proxpero/621366da831116744e5b to your computer and use it in GitHub Desktop.
Selection sort in Swift implemented as an extension on `MutableCollectionType`
// Swift 2.1
extension MutableCollectionType where Self.Generator.Element : Comparable {
/// Return a new sorted collection of the elements in `source`
/// using [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort).
///
/// Complexity O(n^2).
@warn_unused_result(mutable_variant="selectionSortInPlace")
public func selectionSort() -> Self {
var output = self
for primaryIndex in self.indices {
var minimum = primaryIndex
for secondaryIndex in primaryIndex.successor() ..< output.endIndex {
if output[minimum] > output[secondaryIndex] {
minimum = secondaryIndex
}
}
if primaryIndex != minimum {
swap(&output[primaryIndex], &output[minimum])
}
}
return output
}
/// Sort `self` in-place using [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort).
///
/// Complexity O(n^2).
public mutating func selectionSortInPlace() {
for primaryIndex in self.indices {
var minimum = primaryIndex
for secondaryIndex in primaryIndex.successor() ..< self.endIndex {
if self[minimum] > self[secondaryIndex] {
minimum = secondaryIndex
}
}
if primaryIndex != minimum {
swap(&self[primaryIndex], &self[minimum])
}
}
}
}
func testSelectionSort() {
var integers = [2, 10, 5, 3, 8, 4, 7, 9, 6, 1]
// Test that `selectionSort()` returns a sorted array.
assert(integers.selectionSort() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
// Test that `integers` has not changed.
assert(integers == [2, 10, 5, 3, 8, 4, 7, 9, 6, 1])
// mutate `integers` to become sorted.
integers.selectionSortInPlace()
// Test that `integers` is now sorted.
assert(integers == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("All tests pass")
}
testSelectionSort()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment