Selection Sort

Watch selection sort scan the unsorted region for the minimum and swap it to the front. Only n−1 writes total — see why that beats bubble sort on write-expensive memory.

Algorithm

Array

Size48
ComparingSwap/writePivot/keyReadSorted
Speed50×

Comparisons

0

Swaps/writes

0

Step

0/1,577

Reads

0

Aux memory

0

Call depth

1/1

Slow the speed and use Step to match the pseudocode highlight with the bar colors.

Pseudocode

for i ← 0 to n−1

min ← i

for j ← i+1 to n−1

if a[j] < a[min]

min ← j

swap a[i] ↔ a[min]

Time complexity

BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceO(1)
StableNo

Selection sort finds the smallest element in the unsorted region (the purple bar tracks the current minimum) and swaps it into place, one position per pass.

Comparisons are always n(n−1)/2 — O(n²) in every case — but it performs only n−1 swaps, the fewest writes of any comparison sort. That makes it interesting when writes are expensive. It is not stable. Sorting Visualizer

Frequently asked questions

Why use selection sort?
It writes to memory only n−1 times — valuable when writes are costly, e.g. flash storage or heavyweight object moves.
Is selection sort stable?
No — swapping the minimum over equal values can reorder them.

Other algorithms