Skip to content

Instantly share code, notes, and snippets.

@zaguiini
Last active October 29, 2019 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaguiini/d1a0cf1defc82d4c2d350cdf05fe5a4e to your computer and use it in GitHub Desktop.
Save zaguiini/d1a0cf1defc82d4c2d350cdf05fe5a4e to your computer and use it in GitHub Desktop.
Selection sort in plain English
/*
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