Skip to content
SimpleScope

Sorting

Counting sort vs Radix sort

Counting sort and Radix sort both put an array in order, in different ways. Counting sort: count each value, turn the counts into positions and place the values, with no comparisons. Radix sort: sort digit by digit, least significant first, with a stable counting sort for each digit. Neither compares values. Counting sort takes O(n + k) and Radix sort takes O(d (n + k)), where k is the number of possible values (or digit values) and d the number of digits (radix sort).

At a glance

PropertyCounting sortRadix sort
TechniqueCount each value, turn the counts into positions and place the values, with no comparisonsSort digit by digit, least significant first, with a stable counting sort for each digit
Compares values with each otherNoNo
Best case timeO(n + k)O(d (n + k))
Average case timeO(n + k)O(d (n + k))
Worst case timeO(n + k)O(d (n + k))
Extra spaceO(n + k)O(n + k)
Stable (equal values keep their order)YesYes
In place (no extra array)NoNo
Needs sorted inputNoNo

When to choose each

Choose counting sort when

the values are whole numbers in a range k that is small compared with n.

Avoid it when

the range of values is large, or the values are not whole numbers.

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). Counting sort makes no comparisons, so its count is writes only. It includes the k + 1 cells of the count array. Radix sort makes no comparisons, so its count is writes only. The lesson always runs 3 digit passes, even on these one-digit numbers.

InputCounting sortRadix sort
Mixed47141
Already sorted47141
Reversed47141
Nearly sorted47141
Duplicates47141

See them run

More comparisons