Skip to content

Instantly share code, notes, and snippets.

@ChenCodes
Created January 2, 2017 03:20
Show Gist options
  • Save ChenCodes/83aba01d2b621b0de7a72d09d729dcc9 to your computer and use it in GitHub Desktop.
Save ChenCodes/83aba01d2b621b0de7a72d09d729dcc9 to your computer and use it in GitHub Desktop.
var randomNumbers = [5, 4, 3, 2, 1]
func selectionSort(nums: inout [Int]) -> [Int] {
// index of element we're trying to put in the leftmost position
for i in 0..<nums.count - 1 {
// set our smallest element to be the current index's element
var smallestElement = nums[i]
// set our smallest index to be the current index's element
var smallestIndex = i
// iterating through the rest of the array not including the outer loop's index
for j in (i + 1)..<nums.count {
if nums[j] < smallestElement {
smallestElement = nums[j]
smallestIndex = j
}
}
// perform the swap between the smallest element and the current outer loop index element
let temp = nums[i]
nums[i] = nums[smallestIndex]
nums[smallestIndex] = temp
}
return nums
}
print(selectionSort(nums: &randomNumbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment