Selection Sort

The second sorting method we used is called Selection Sort.

Completed Code

function selectionSort(arr) {
  var minIdx, temp,
    len = arr.length;
  for (var i = 0; i < len; i++) {
    minIdx = i;
    for (var j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    temp = arr[i];
    arr[i] = arr[minIdx];
    arr[minIdx] = temp;

  }
  return arr;

}
console.log(selectionSort([207, 150, 71, -25, 369, 246, -13, 22, 150]));

Explanation

  1. selectionSort() searches for the element with the lowest value.

  2. The lowest value is -25 with an index of 3.

  3. -25 swaps places with the first element in the array 207. This way we now have the lowest value starting off our array.

  4. Repeat the process, finding the next smallest value and putting it to the right of -25.

  5. Repeat the process until the array is properly sorted.

Variables Explanation

  • minIdx - the index of our smallest value. It is initially set to the first element in our array.

  • temp - a temporary variable to easily allow the value of arr[minIdx] to change.

  • i and j - the indexes of the elements that are being compared.

Last updated