Skip to content

Instantly share code, notes, and snippets.

@MohdSaifulM
Created December 19, 2022 16:15
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 MohdSaifulM/666acd0b37926f9a4b20cd96480a8ba7 to your computer and use it in GitHub Desktop.
Save MohdSaifulM/666acd0b37926f9a4b20cd96480a8ba7 to your computer and use it in GitHub Desktop.
Algorithms - Sorting (Selection Sort)
/*
Selection sort
- Time complexity O(n^2)
- Best use case if we want to limit the swapping of elements
*/
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
// Store first element as the smallest value
let minIndex = i;
// Compare this to the next item in the array until we find the smallest in the array
for (let j = i + 1; j < arr.length; j++) {
// If smaller number is found, store new minIndex
if (arr[j] < arr[minIndex]) minIndex = j;
}
// If the new minimum is not the value of the index we begin with swap the two indexes
if (i !== minIndex) [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
}
return arr;
}
selectionSort([3, 23, 67, 2, 5, 76, 54, 90, 102, 4, 7, 32, 13]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment