Skip to content

Instantly share code, notes, and snippets.

@0xMarK
Created November 29, 2020 19:58
Show Gist options
  • Save 0xMarK/1feafd19f9f2d57e4bd5e8605a59e1e5 to your computer and use it in GitHub Desktop.
Save 0xMarK/1feafd19f9f2d57e4bd5e8605a59e1e5 to your computer and use it in GitHub Desktop.
Selection Sort
func selectionSort(_ array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
var sorted = array
var smallestIndex = 0
for i in 0..<array.count {
for j in (i + 1)..<array.count {
if sorted[j] < sorted[smallestIndex] {
smallestIndex = j
}
}
let smallest = sorted[smallestIndex]
sorted[smallestIndex] = sorted[i]
sorted[i] = smallest
}
return sorted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment