Skip to content

Instantly share code, notes, and snippets.

@tcelovsky
Created Oct 26, 2021
Embed
What would you like to do?
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