AlgoLab

O(n²)·O(1) space·not stable
645559896316373459948511843281951114277

Starting selection sort on an array of 20 items.

Starting selection sort on an array of 20 items.
  1. 1for each position from the start to the second-to-last
  2. 2assume this position already holds the smallest remaining value
  3. 3compare it with each later value to look for a smaller one
  4. 4a smaller value was found, so remember its position instead
  5. 5swap the smallest remaining value into this position
  6. 6the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n²)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableNo
n² at n=20 predicts 400; this run took 0.

Selection sort

Selection sort divides the array into a sorted prefix and an unsorted remainder. For each position, it scans the entire unsorted remainder to find the smallest value there, then swaps that value into place.

When it is the right choice

Selection sort is worth using when writes are far more expensive than comparisons, since it makes at most n − 1 swaps in total, no matter the input. Otherwise it is not competitive: it makes the same number of comparisons on every input — sorted, reversed or random — so it cannot benefit from data that is already partly ordered the way insertion sort can.

How it works

Worth noticing

Cost

Best
O(n²)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
No

Worth comparing

All algorithms