Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active July 26, 2018 21:32
Show Gist options
  • Save derekli66/7435d8fcba6b0404a954b567e86be8b1 to your computer and use it in GitHub Desktop.
Save derekli66/7435d8fcba6b0404a954b567e86be8b1 to your computer and use it in GitHub Desktop.
// Using Playground
import Foundation
func selectionSort(_ numbers: Array<Int>) -> Array<Int>
{
var nums = numbers
if (nums.count <= 1) { return nums }
for i in 0..<nums.count {
var currentIdx = i
for j in i..<nums.count {
// if value at currentIdx is greater than the value at index j
// Then change the currentIdx to point to smallest one
if (nums[currentIdx] > nums[j]) {
currentIdx = j
}
}
let temp = nums[i]
nums[i] = nums[currentIdx]
nums[currentIdx] = temp
}
return nums
}
var array = [5,4,3,2,1]
let sorted = selectionSort(array)
print(sorted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment