Skip to content

Instantly share code, notes, and snippets.

@fortunee
Created March 10, 2023 05:31
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 fortunee/dca465220c19f6503a8c9b0fef53ab0a to your computer and use it in GitHub Desktop.
Save fortunee/dca465220c19f6503a8c9b0fef53ab0a to your computer and use it in GitHub Desktop.
Selection sort basically places the smaller values into a sorted position in the array by selecting lowest value and swapping it with item at the beginning
/**
* PSEUDOCODE
* - start a for loop
* - store the index of the first item in the array as the current minimum
* - start a second nested for loop which starts iterating from the next item
* - compare each item with the item at the stored minimum index
* - if any item is lower then reassign it to be the stored minimum
* - at the end of the of firt iteration for the second loop
* - then swap the item at stored minimum index with the item at the
* - current iteration of the outer for loop
* - ONLY if it's not the same
*/
function selectionSort(array) {
for (let i = 0; i < array.length; i++) {
let minIndex = i;
for (let j = i + 1; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j
}
}
// swap
if (i != minIndex) {
let temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment