Selection sort

Find the smallest remaining value and swap it into place, one position at a time: always O(n²) comparisons, but at most n − 1 swaps.

Description

Selection sort builds the sorted array from the left. On each pass it scans the unsorted part to select the smallest value, then swaps it into the first unsorted position. After k passes, the first k positions hold the k smallest values in order.

It always makes about n²/2 comparisons, whatever the input, so it's never fast. Its one distinctive property is that it makes at most n − 1 swaps, the fewest of any simple sort, which can matter when writes are much more expensive than reads, as with some flash memory.

The long-distance swap makes it unstable: equal values can change their relative order.

How it works

203172931485next

The sorted part grows from the left; 1 is the smallest remaining value

  1. index 0: 2
  2. index 1: 3
  3. index 2: 7
  4. index 3: 9
  5. index 4: 1
  6. index 5: 8
The sorted part grows from the left; 1 is the smallest remaining value

Step through: selection sort

291014371354122

Step 1 of 37Start with 8 values.

0 comparisons, 0 swaps
New data: , , ,

Complexity

OperationAverageWorst
Sort (any input)Even sorted input needs every comparison.O(n²)O(n²)
SwapsAt most n − 1.O(n)O(n)

Space: O(1)

TypeScript implementation

Selection sort, counting comparisons and swaps.

selection-sort.ts
// Selection sort: repeatedly select the minimum of the unsorted part.

export function selectionSort(a: number[]): { comparisons: number; swaps: number } {
  let comparisons = 0, swaps = 0;
  for (let i = 0; i < a.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < a.length; j++) {
      comparisons++;
      if (a[j] < a[min]) min = j;
    }
    if (min !== i) {
      [a[i], a[min]] = [a[min], a[i]];
      swaps++;
    }
  }
  return { comparisons, swaps };
}

export function demo(): string[] {
  const a = [29, 10, 14, 37, 13, 5, 41, 22];
  const r = selectionSort(a);
  const sorted = Array.from({ length: 8 }, (_, i) => i);
  const s = selectionSort(sorted);
  return [
    `[${a.join(", ")}]: ${r.comparisons} comparisons, ${r.swaps} swaps`,
    `already sorted: still ${s.comparisons} comparisons, ${s.swaps} swaps`,
  ];
}

When to use it

Use it when

  • Writes are very expensive compared with reads, and n is small.
  • Teaching the idea of an invariant: the left part is always sorted and final.

Avoid it when

  • Almost always: insertion sort is faster on typical data, and built-in sorts are far faster.
  • You need stability.

Pitfalls

  • Expecting it to speed up on sorted input: it doesn't.
  • Assuming stability: the swaps reorder equal values.

Alternatives

Insertion sort

Choose it when you want a simple, stable sort that's fast on nearly sorted data.

Heapsort

Choose it when you like the idea of repeatedly selecting the extreme value, but need O(n log n): a heap makes the selection fast.