Skip to content
SimpleScope

Sorting

Selection sort vs Heap sort

Selection sort and Heap sort both put an array in order, in different ways. Selection sort: repeatedly pick the smallest remaining value. Heap sort: build a max-heap in the array, then repeatedly move the largest value to the end. In the worst case heap sort takes O(n log n) while selection sort takes O(n²), so heap sort scales better on large inputs.

At a glance

PropertySelection sortHeap sort
TechniqueRepeatedly pick the smallest remaining valueBuild a max-heap in the array, then repeatedly move the largest value to the end
Best case timeO(n²)O(n log n)
Average case timeO(n²)O(n log n)
Worst case timeO(n²)O(n log n)
Extra spaceO(1)O(1)
Stable (equal values keep their order)NoNo
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose selection sort when

writing to memory is expensive, since it makes at most n - 1 swaps.

Avoid it when

the data is large, or you hope sorted input will be fast.

Choose heap sort when

you need a guaranteed O(n log n) time and almost no extra memory.

Avoid it when

you need a stable sort, or the fastest sort on typical data.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes).

InputSelection sortHeap sort
Mixed2943
Already sorted2153
Reversed2740
Nearly sorted2350
Duplicates3136

See them run

More comparisons