Last active
October 29, 2019 04:05
-
-
Save zaguiini/d1a0cf1defc82d4c2d350cdf05fe5a4e to your computer and use it in GitHub Desktop.
Selection sort in plain English
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
/* | |
Time complexity: O(nˆ2) since it has two nested loops | |
Space complexity: O(1) since it uses a reference to something that already exists and does not create new arrays | |
*/ | |
const selectionSort = array => { | |
for (let arrayIndex = 0; arrayIndex < array.length - 1; arrayIndex++) { | |
let minIndex = arrayIndex | |
for (let subArrayIndex = arrayIndex + 1; subArrayIndex < array.length; subArrayIndex++) { | |
if (array[subArrayIndex] < array[minIndex]) { | |
minIndex = subArrayIndex | |
} | |
} | |
const minIndexElement = array[minIndex] | |
array[minIndex] = array[arrayIndex] | |
array[arrayIndex] = minIndexElement | |
} | |
return array | |
} | |
const unsortedArray = [64, 25, 12, 22, 11] | |
selectionSort(unsortedArray) // [11, 12, 22, 25, 64] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment