Last active
April 10, 2020 08:42
-
-
Save leolanese/3ebe0b3dfccc620c6aa7a5e5e36429ee to your computer and use it in GitHub Desktop.
Sorting algorithms JS: Selection Sort Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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