Created
August 31, 2018 01:05
-
-
Save 0xABCCBA/34b4a84a901a09d7dc70324d155509ee to your computer and use it in GitHub Desktop.
SelectionSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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