Skip to content

Instantly share code, notes, and snippets.

@leolanese
Last active April 10, 2020 08:42
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 leolanese/3ebe0b3dfccc620c6aa7a5e5e36429ee to your computer and use it in GitHub Desktop.
Save leolanese/3ebe0b3dfccc620c6aa7a5e5e36429ee to your computer and use it in GitHub Desktop.
Sorting algorithms JS: Selection Sort Implementation
//
// Selection Sort Implementation
//
function selectionSort (unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
for (let i = 0; i < unsortedArray.length; i++) {
let minIndex = i;
for (let j = i + 1; j < unsortedArray.length; j++) {
if (unsortedArray[j] < unsortedArray[minIndex]) {
minIndex = j;
}
}
// Swap the current element with the smaller element
[unsortedArray[i], unsortedArray[minIndex]] = [unsortedArray[minIndex], unsortedArray[i]]; // ES6 Swap
}
return unsortedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment