Counting and Radix Sort
How counting sort and radix sort order integer keys in linear time without comparisons, when they apply, and what interviewers ask about them.
On this page
Counting sort orders items whose keys are small whole numbers by counting how many items have each key and then placing every item directly at its final position. It never compares two items, so it runs in O(n + k) time, where k is the number of possible key values. Radix sort applies counting sort to one digit at a time, which extends the idea to large numbers and fixed-length strings.
Comparison sorts such as merge sort cannot do better than O(n log n). If you need to sort a million exam scores between 0 and 100, comparing pairs of scores wastes effort, because there are only 101 distinct values to tell apart.
Why comparison sorts cannot beat O(n log n)
Merge sort, quicksort and heap sort learn the order only by asking whether one item is smaller than another. For n items there are n factorial possible orders, and each comparison can at best cut the remaining possibilities in half. Reaching a single order therefore takes at least about log₂ of n factorial comparisons, which is on the order of n log n, so no comparison sort can beat that bound in the worst case.
Counting sort avoids the bound because it does not compare items. It uses each key as an array index, which is only possible when the keys are integers in a known range.
How counting sort works
Assume every key is a whole number from 0 to k - 1. The algorithm has three steps.
- Count how many items have each key.
- Work out where the items with each key start in the output. The items with key 0 start at position 0, the items with key 1 start right after them, and in general each key starts at the sum of the counts of all smaller keys. This running total is a prefix sum of the counts.
- Go through the input in its original order. Put each item at the start position for its key, then move that start position forward by one.
Because step 3 reads the input in order, items with equal keys end up in the same relative order as in the input, so the sort is stable. Radix sort depends on this. In the trace below, the letters distinguish equal keys: 3a and 3b both have key 3, and 3a comes first in the input.
for each item: count[key] += 1start[0] = 0for v from 1 to k - 1: start[v] = start[v - 1] + count[v - 1]for each item, in input order: out[start[key]] = item start[key] += 1- input03a11a23b30a42a51bcount00102030
1There are six items with keys 0 to 3, so the algorithm uses
k = 4counters. - input03a11a23b30a42a51bcount01122132
2One pass over the input fills in the counts.
- input03a11a23b30a42a51bstart00112334out012345
3Each key starts after all items with smaller keys, so key 0 starts at 0, key 1 at 1, key 2 at 1 + 2 = 3, and key 3 at 3 + 1 = 4.
- input03ax11a23b30a42a51bstart00112335out012343a5
4
3ahas key 3, which starts at 4. The algorithm puts it atout[4]and moves the start for key 3 to 5. - input03a11ax23b30a42a51bstart00122335out011a2343a5
5
1agoes toout[1], and the start for key 1 moves to 2. - input03a11a23bx30a42a51bstart00122336out011a2343a53b
6
3bgoes toout[5], right after3a, because 3's start already moved past it. - input03a11a23b30ax42a51bstart01122336out00a11a2343a53b
7
0agoes toout[0], since key 0 starts at position 0. - input03a11a23b30a42ax51bstart01122436out00a11a232a43a53b
8
2agoes toout[3], the start position for key 2. - input03a11a23b30a42a51bxstart01132436out00a11a21b32a43a53b
9
1bgoes toout[2], right after1a. - out00a11a21b32a43a53b
- comparisons
- 0
10The output is sorted, with
1abefore1band3abefore3b. The algorithm made two passes over the 6 items, one pass over the 4 counters, and no comparisons.
The key function converts each item to its whole-number key, so the same code sorts records as well as plain numbers.
// key(item) must be a whole number from 0 to k - 1
function countingSortBy(items, key, k) {
const count = new Array(k).fill(0);
for (const item of items) count[key(item)]++;
const start = new Array(k).fill(0); // start[v] = items with key < v
for (let v = 1; v < k; v++) start[v] = start[v - 1] + count[v - 1];
const out = new Array(items.length);
for (const item of items) {
out[start[key(item)]++] = item; // input order: stable
}
return out;
}
countingSortBy([3, 1, 3, 0, 2, 1], (x) => x, 4); // [0, 1, 1, 2, 3, 3]# key(item) must be a whole number from 0 to k - 1
def counting_sort_by(items, key, k):
count = [0] * k
for item in items:
count[key(item)] += 1
start = [0] * k # start[v] = items with key < v
for v in range(1, k):
start[v] = start[v - 1] + count[v - 1]
out = [None] * len(items)
for item in items: # input order: stable
out[start[key(item)]] = item
start[key(item)] += 1
return out
counting_sort_by([3, 1, 3, 0, 2, 1], lambda x: x, 4) # [0, 1, 1, 2, 3, 3]How radix sort works
Counting sort needs one counter for every possible key. That is fine for scores from 0 to 100, but a counter array for order numbers up to a billion would be far too large.
Radix sort avoids this by sorting one digit at a time. Each pass is a stable counting sort on a single digit, so it needs only 10 counters in base 10. The passes must go from the least significant digit to the most significant one, so the first pass uses the ones digit, then the tens digit, then the hundreds digit, and so on.
- nums0512103824073223409553406018
1The input has seven numbers, written with three digits each. The largest is 512, so three passes are enough.
- by ones0340151222233095440750386018
2Pass 1 is a stable sort by the ones digit. 038 and 018 both end in 8, so they keep their input order.
- by tens0407151220183223403853406095
3Pass 2 is a stable sort by the tens digit. 512 and 018 tie on the tens digit 1, and 512 stays first because pass 1 placed it first, since its ones digit 2 is smaller than 8.
- by tens0407151220183223403853406095
4The numbers are now in order by their last two digits: 07, 12, 18, 23, 38, 40, 95. In general, after pass
pthe numbers are sorted by their lastpdigits. - by hundreds0018103820953223434054076512
5Pass 3 is a stable sort by the hundreds digit. 018, 038 and 095 tie on 0, so stability keeps the order the earlier passes gave them.
- sorted0018103820953223434054076512
- passes
- 3
- counters per pass
- 10
6The list is sorted after 3 passes, and each pass used only 10 counters.
This works because the last pass sorts by the most significant digit, and stability means that numbers tied on that digit keep the order the earlier passes gave them, which is already correct for the lower digits. If any pass were not stable, it would destroy the work of the previous passes.
// non-negative integers; uses countingSortBy from above
function radixSort(nums) {
const biggest = nums.reduce((m, x) => Math.max(m, x), 0);
for (let place = 1; place <= biggest; place *= 10) {
nums = countingSortBy(nums, (x) => Math.floor(x / place) % 10, 10);
}
return nums;
}
radixSort([512, 38, 407, 223, 95, 340, 18]);
// [18, 38, 95, 223, 340, 407, 512]# non-negative integers; uses counting_sort_by from above
def radix_sort(nums):
biggest = max(nums, default=0)
place = 1
while place <= biggest:
nums = counting_sort_by(nums, lambda x: x // place % 10, 10)
place *= 10
return nums
radix_sort([512, 38, 407, 223, 95, 340, 18])
# [18, 38, 95, 223, 340, 407, 512]Time and space complexity
| Approach | Time | Space | Why |
|---|---|---|---|
| Counting sort | O(n + k) | O(n + k) | The sort makes passes over the n items and over the k counters, so it is fast when k is not much larger than n. |
| Radix sort | O(d × (n + b)) | O(n + b) | There are d digits, and each digit is one counting sort with b counters. In base 10, b is 10. |
Counting sort needs O(n + k) time and space. For radix sort with d digits in base b, each pass costs O(n + b), so the total is O(d × (n + b)). For 32-bit integers handled one byte at a time, d is 4 and b is 256, which is linear in n with a small constant.
When to use counting sort and radix sort
Counting sort fits integer keys from a small range, where k is no larger than a small multiple of n. Radix sort fits fixed-width integers, dates and fixed-length strings, where d is small. For ordinary code, the language's built-in sort is almost always the right choice, because it handles every key type and is fast enough.
Variants and when they do not apply
Negative numbers
A negative key cannot be used as an array index. The usual fix is to subtract the minimum value from every key, so that the smallest key becomes 0 and the counter array has max - min + 1 entries. Radix sort handles negatives either by the same shift or by sorting the negative and non-negative numbers separately.
Least significant digit first and most significant digit first
The version in this lesson processes the least significant digit first (LSD radix sort). It is simple, stable and works for any fixed-width keys. The alternative is to process the most significant digit first (MSD radix sort), which splits the items into buckets by their first digit and then sorts each bucket by the next digit. MSD is the better fit for strings of different lengths, because it can stop early once a bucket holds a single item, but it needs recursion and more bookkeeping.
When these sorts do not apply
Counting sort does not apply when the key range is much larger than the number of items, for example one million random 64-bit ids, because the counter array would not fit in memory and filling it would cost more than a comparison sort. Neither sort applies to items that have no integer or fixed-length key, such as objects ordered by a custom comparison function.
Pitfalls and nuances
Choosing the base
A larger base means fewer passes but more counters per pass. Base 10 is convenient for tracing by hand, but real implementations usually use base 256 so that each pass reads one byte. A 32-bit integer then needs 4 passes with 256 counters each, instead of 10 passes in base 10.
Radix sort is not always faster than O(n log n)
Radix sort does about d passes over the data, while a comparison sort does about log₂ n levels of work. If the keys are long, so that d is larger than log₂ n, radix sort does more work than merge sort. It wins when the keys are short compared with the number of items.
In the interview
The signals are a problem that asks you to sort or order values and gives a bounded range of integers (ages, scores, characters, values from 0 to 1,000), or one that asks for better than O(n log n) time. The same counting idea appears whenever the answer is a frequency array: counting character frequencies in a string, finding the most common value in a small range, or checking whether two strings are anagrams. State the range out loud ("the values are between 0 and 100, so I can count them") because that observation is what the interviewer is looking for.
Questions to expect:
- "Why is this faster than O(n log n)?" The O(n log n) bound applies only to sorts that work by comparing items. Counting sort uses the key as an array index, so it does not compare anything, but it needs the keys to be small integers.
- "What is the time and space complexity?" Counting sort is O(n + k) in both time and space, where k is the size of the key range. If k grows much faster than n, it becomes slower than a comparison sort.
- "Why does stability matter?" Radix sort sorts one digit at a time, and each pass must keep the order produced by the previous passes among items that tie on the current digit. Stability is also needed when you sort records and want equal keys to stay in input order.
- "Why does radix sort start from the least significant digit?" The last pass has the final say about order, so it must use the most significant digit. Earlier passes only decide the order of items that tie on later digits.
- "How would you sort negative numbers?" Subtract the minimum value from every key so that all keys are at least 0, and use the shifted value as the counter index. The shift costs one extra pass to find the minimum and does not change the complexity. Alternatively, sort the negative and non-negative parts separately and join them.
- "How many passes does radix sort need, and can you change that?" It needs one pass per digit of the largest value. Using a larger base such as 256 reduces the number of passes at the cost of a bigger counter array, and for 32-bit integers it brings the count down to 4 passes.
- "Is it in place?" No. It needs an output array of size n and a counter array of size k.
- "When would you not use it?" When the key range is large compared with the number of items, the counter array is too big to be worth filling. I would also avoid it when the items can only be compared, such as objects with a custom ordering, because there is no integer key to count.
The counts for keys 0 to 3 are [2, 0, 3, 1]. At which output position does the first item with key 3 go?
Radix sort is applied to [21, 12, 22, 11]. What is the order after the ones-digit pass?
You must sort 1 million user ids, each a random number up to 1018. Is counting sort a good fit?
Why must radix sort process the ones digit before the hundreds digit when it uses stable counting passes?
What to practise next
Once data is sorted, you can find any value in it in O(log n) time with binary search, which is the next lesson.