Skip to main content

Selection Sort

Scan for the minimum of the unsorted region, one swap per round, comparisons never shrink.

time O(n²)space O(1)Read the lesson
BeginnerO(n²)

Scan for the minimum of the unsorted region, one swap per round, comparisons never shrink.

step 1 / 27

What's happening

Selection sort finds the smallest remaining value and swaps it into place, one position per round.

comparisons: 0swaps: 0writes: 0
comparingswappingkey heldwritingpivotfinal position

One swap per round, maximum. But the scan never shrinks its effort, comparisons stay ~n²/2 even on sorted input. Try “1, 2, 3, 4, 5, 6” and watch the comparison counter.

Understand the algorithm

time O(n²)space O(1)

What it is

Selection sort finds the minimum of the unsorted region and swaps it into place, one final position per round.

Why it matters

It isolates a single idea, selection, with the minimum possible number of swaps (at most n−1). That makes it the go-to example when writes are expensive, and a clean illustration of the difference between comparisons and writes.

How it works

  1. 1Scan the unsorted region for its smallest element.
  2. 2Swap it with the first unsorted position.
  3. 3The sorted prefix grows by one; the scan region shrinks by one.
  4. 4Repeat until one element remains, it is already in place.

Real-world uses

  • Sorting when writes are far costlier than reads (e.g., flash memory wear)
  • Small datasets where simplicity wins
  • Teaching the comparison/write distinction

Strengths

  • At most n − 1 swaps, the minimum among simple sorts
  • O(1) space, in place
  • Predictable O(n²) comparisons regardless of input order

Limitations

  • O(n²) comparisons even on sorted input, no early exit
  • Not stable, long swaps reorder equal keys
  • Slower than insertion sort on nearly-sorted data

Notice how many comparisons an already-sorted array still costs.