Created
January 2, 2017 03:20
-
-
Save ChenCodes/83aba01d2b621b0de7a72d09d729dcc9 to your computer and use it in GitHub Desktop.
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
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