Selection sort is like insertion sort in the way that you can think of it as dividing the array into two parts, sorted and unsorted. The sorted part will be on the left side and it will start off empty. Each pass through the array will take the smallest element that is left and add it to end of the sorted side.

function selectionSort(arr) {              
    for (let i = 0; i < arr.length - 1; i++) {
        let min = i;
        for (let j = i+1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min=j; 
            }
        }
        if (min != i) {
            let tmp = arr[i]; 
            arr[i] = arr[min];
            arr[min] = tmp;      
        }
    }
    return arr;
}
  • On each pass of the outer for loop, arr[i] is the last index of the sorted array.
  • min will keep track of the index with the lowest value and will start out as the same index as arr[i].
  • All elements to the right of arr[i] make up the unsorted array.
  • The nested loop compares each element in the unsorted array to the value of arr[min].
  • If its value is lower than arr[min] then its index will now be set to min.
  • When each pass of the nested for loop is finished, arr[min] will be the lowest value in the unsorted array.
  • Then arr[min] is added to the end of the sorted array by swapping places with arr[i].
  • If arr[i] already had the lowest value it will stay where it is.
  • Then the outer loop moves to the next index and the process is repeated.
  • The outer loop returns the array after the next to last index because the last index will already be sorted.
SPEED
3s
Array
[]
min
0
Unsorted
[]
Sorted Array
[]