Skip to content

Instantly share code, notes, and snippets.

@0xABCCBA
Created August 31, 2018 01:05
Show Gist options
  • Save 0xABCCBA/29efe513bb446fd63555d81c880faf2a to your computer and use it in GitHub Desktop.
Save 0xABCCBA/29efe513bb446fd63555d81c880faf2a to your computer and use it in GitHub Desktop.
SelectionSort
func selectionSort(_ array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
var a = array
for x in 0..<(a.count - 1) {
var lowest = x
for y in x + 1 ..< a.count {
if a[y] < a[lowest] {
lowest = y
}
}
if x != lowest {
a.swapAt(x, lowest)
}
}
return a
}
public func selectionSort<Element>(_ array: inout [Element]) where Element: Comparable {
guard array.count >= 2 else { return }
for current in 0..<(array.count - 1) {
var lowest = current
for other in (current + 1)..<array.count {
if array[lowest] > array[other] {
lowest = other
}
}
if lowest != current {
array.swapAt(lowest, current)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment