Skip to content

Instantly share code, notes, and snippets.

@Giagnus64
Created January 1, 2020 23:34
Show Gist options
  • Select an option

  • Save Giagnus64/49eafc6368a6318d2a3c08ecd2de31f4 to your computer and use it in GitHub Desktop.

Select an option

Save Giagnus64/49eafc6368a6318d2a3c08ecd2de31f4 to your computer and use it in GitHub Desktop.
SelectionSort
function selectionSort(arr){
let smallestIndex = 0;
let currentIndex = 1;
let beginningIndex = 0;
//loop until the sorted section is the full array
while(beginningIndex < arr.length){
//loop over the array until the currentIndex has reached the last element
while(currentIndex < arr.length){
//keep track of the smallest index by comparing it to the current index
if(arr[smallestIndex] > arr[currentIndex]){
smallestIndex = currentIndex;
}
//add to the current index to iterate through the array
currentIndex++;
}
// after iterating through the array once, if the smallest number isn't at the sorted section, swap the two
if(smallestIndex !== beginningIndex){
swap(arr, smallestIndex, beginningIndex)
}
//add to the beginning index to incorporate the new sorted section
beginningIndex++;
//start the current index at 1 above the sorted section
currentIndex = beginningIndex + 1;
//reset the smallest index to the beginningIndex
smallestIndex = beginningIndex;
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment