Skip to content

Instantly share code, notes, and snippets.

@IdrissDimson
Created June 3, 2021 04:12
Show Gist options
  • Save IdrissDimson/5ab4973681b960f35e93eea929096817 to your computer and use it in GitHub Desktop.
Save IdrissDimson/5ab4973681b960f35e93eea929096817 to your computer and use it in GitHub Desktop.
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