Algorithm

Selection Sort Algorithm

Selection sort does exactly what the name says. Scan the unsorted portion, select the smallest element, swap it into position. Repeat.

19 Mar 2024

Selection Sort Algorithm

Selection sort does exactly what the name says. Scan the unsorted portion, select the smallest element, swap it into position. Repeat.

It's the algorithm you'd naturally invent if someone handed you a deck of cards and said "sort these." Look through all of them, find the smallest, put it first. Find the next smallest, put it second. And so on.

The intuition

Divide the array into two regions: sorted (left) and unsorted (right). Each pass finds the minimum in the unsorted region and swaps it with the first unsorted element.

Javascript
function selectionSort(arr) {
    const n = arr.length;

    for (let i = 0; i < n - 1; i++) {
        let minIndex = i;

        for (let j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        if (minIndex !== i) {
            [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
        }
    }

    return arr;
}

Complexity

  • Time: O(n²) — always, even if the array is already sorted. The inner loop runs regardless.
  • Space: O(1) — sorts in-place.

When to use it (and when not to)

Selection sort has one advantage over bubble sort: it minimizes the number of swaps (at most n-1). If swaps are expensive — say you're moving large records on disk — that matters.

But for almost everything else, it's too slow. Merge sort and quicksort run in O(n log n). Use selection sort to understand sorting concepts. Use something else in production.

Keep reading