Skip to content

Instantly share code, notes, and snippets.

@tcelovsky
Created October 26, 2021 20:56
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 tcelovsky/4c7b1b5a852adacf13ba7a3604000f79 to your computer and use it in GitHub Desktop.
Save tcelovsky/4c7b1b5a852adacf13ba7a3604000f79 to your computer and use it in GitHub Desktop.
Selection Sort Algorithm
function selectionSort(array) {
for (let i = 0; i < array.length - 1; i++) { // for loop iterates through each item in the array, stopping with the second to last item. This is because in the next loop we will compare `i` to its neighbor `i + 1` in the array, therefore, we have to stop this initial loop one index short of the full array length;
let minimum=i; // set the first element as `minimum`;
for (let j = i + 1; j < array.length; j++) { // for loop iterates through each item in the unsorted sublist;
if (array[j] < array[minimum]) { // if statement checks whether the following element of the unsorted sublist is smaller than the current `minimum`;;
minimum=j; // if it is, assign `minimum` to that element ; otherwise, do nothing;
}
}
[array[i], array[minimum]] = [array[minimum], array[i]]; // move `minimum` to the end of the sorted sublist;
}
return array; // return the now sorted array.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment