Skip to content
SimpleScope

Sorting

Heap sort vs Radix sort

Heap sort and Radix sort both put an array in order, in different ways. Heap sort: build a max-heap in the array, then repeatedly move the largest value to the end. Radix sort: sort digit by digit, least significant first, with a stable counting sort for each digit. Radix sort compares no values: it takes O(d (n + k)), where k is the number of possible values (or digit values) and d the number of digits (radix sort), while heap sort takes O(n log n) in the worst case. Radix sort is faster only when k and d are small compared with n; heap sort makes no assumption about the values.

At a glance

PropertyHeap sortRadix sort
TechniqueBuild a max-heap in the array, then repeatedly move the largest value to the endSort digit by digit, least significant first, with a stable counting sort for each digit
Compares values with each otherYesNo
Best case timeO(n log n)O(d (n + k))
Average case timeO(n log n)O(d (n + k))
Worst case timeO(n log n)O(d (n + k))
Extra spaceO(1)O(n + k)
Stable (equal values keep their order)NoYes
In place (no extra array)YesNo
Needs sorted inputNoNo

When to choose each

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.

Choose radix sort when

many integers or fixed-length keys have few digit positions (d is small).

Avoid it when

the array is small, or the keys are long.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes). Radix sort makes no comparisons, so its count is writes only. The lesson always runs 3 digit passes, even on these one-digit numbers.

InputHeap sortRadix sort
Mixed43141
Already sorted53141
Reversed40141
Nearly sorted50141
Duplicates36141

See them run

More comparisons