Skip to main content

Larry's Blog 🌊

math, code and fun



Selection Sort

  | #Algorithms

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.

The algorithm maintains two subarrays in a given array. But be noted that we don’t create two arrays, but operate the whole process within the original array.

  • The subarray which already sorted (left part).
  • The remaining subarray was unsorted (right part).

From the left most element, we itinerate the whole array one by one. In every itineration of the selection sort, the minimum element (considering ascending order) from the unsorted rigth subarray is picked and moved to the sorted subarray.

selction sort

Illustration of Selection Sort

Below is the implementation of the algorithm, we use recursion again:

// swap function
const swap = (arr, a, b) => {
  const temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
};

// recursion realization of the selection sort
const selectRecur = (array, n) => {
  if (n === array.length) return array;

  for (let i = n; i < array.length; i++) {
    if (array[n] > array[i]) swap(array, n, i);
  }

  return selectRecur(array, n + 1);
};

// we test by a random array
const arr = [12, 10, 9, 7, 8, 5, 3, 4, 7, 7, 4, 3, 2, 1, 0, 2];
console.log(selectRecur(arr, 0));


About Larry Cui

Photo of Larry Cui

A greenhorn coder and a big fan of math.