Skip to main content
Beginner ~10 min read

Selection Sort

Scan for the minimum, swap it into place, repeat. Minimal swaps, maximal comparisons, and a useful mental model.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

Selection sort divides the array into a sorted prefix and an unsorted suffix. Each round: scan the whole unsorted region to find its minimum, then swap that minimum with the region's first element. The sorted prefix grows by one; the unsorted region shrinks by one. After n-1 rounds, done.

The interesting property is the swap count: exactly one swap per round, at most n-1 total, the fewest of any classic O(n²) sort. Comparisons, though, are unbudgeable: each round scans everything remaining, n-1 + n-2 + ... + 1 ≈ n²/2 total, regardless of the input's order. Already-sorted input costs the same comparisons as reversed input.

Implementation

selection-sort.js
// Pure: returns a new sorted array. NOT stable (long-distance swaps).
function selectionSort(input) {
  const arr = [...input];
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let minIdx = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) minIdx = j;   // track, don't move
    }
    if (minIdx !== i) {
      [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];  // exactly one swap
    }
  }
  return arr;
}
Operation / caseCostNotes
Comparisons (any input)O(n²)always ~n²/2, order doesn't matter
SwapsO(n)≤ n−1: its signature strength
SpaceO(1)in-place
Stable?Nolong-distance swaps reorder equal keys

Check your understanding

  1. 1.What is the maximum number of swaps selection sort performs on n elements?
  2. 2.Selection sort on an ALREADY SORTED array costs how many comparisons?
  3. 3.The invariant after round k of selection sort is:

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Selection Sort

Play, pause, and scrub the real algorithm step by step.

Play it

Sorting Arena

Sort the bar array yourself using swaps, then find out how your move count compares to the theoretical minimum…

Keep going