Created
June 3, 2021 04:12
-
-
Save IdrissDimson/5ab4973681b960f35e93eea929096817 to your computer and use it in GitHub Desktop.
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
function selectionSort(arr){ | |
for (var i = 0; i < arr.length; i++) { | |
let min = i; | |
// if the array index is less than the min, the min is equal to j. | |
// this finds the smallest number in the iteration. | |
for(let j = i + 1; j < arr.length; j++){ | |
if(arr[j] < arr[min]){ | |
min = j; | |
} | |
} | |
// if the smallest element is not the first element, swap the element with whatever element is first. | |
if(min != i){ | |
let tmp = arr[i]; | |
arr[i] = arr[min]; | |
arr[min] = tmp; | |
} | |
} | |
return arr; | |
} | |
let arr = [5, 3, 1, 6, 2, 4, 7]; | |
selectionSort(arr); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment