Counting sort and radix sort
Two sorts that never compare one item with another: count how often each value occurs, then extend the trick to long keys one digit at a time.
In 30 seconds
Most sorting methods work by comparing pairs of items. Counting sort does not: it counts how many times each value occurs, then writes the values back out in order. With n items and k possible values that takes about n + k steps.
It only pays when the range of values is small. Radix sort lifts that limit by sorting on one digit at a time, last digit first, with a stable sort for each pass.
Both need keys that behave like whole numbers.
Counting sort and radix sort, step by step
Real code replaces the bucket queues with positions computed from the counts (prefix sums). Step counts are rough: they leave out writing the output, and a bucket drop does not cost the same as a comparison.
- Step 1: Keys as addresses. Eight keys, each a whole number from 0 to 4. Because the possible values are so few, we can give every value its own counter and use the key itself to find it. No key is ever compared with another.
- Step 2: Count each value. Walk the input once. Each key adds one to its own counter. After eight keys the counters say there is one 0, three 1s, no 2s, two 3s and two 4s. That tally holds everything needed to write the sorted order.
- Step 3: Read the counts back. Now walk the counters from the smallest value up. Each one writes its value as many times as it counted: one 0, three 1s, nothing for 2, two 3s, two 4s. The output is sorted, and the keys were never compared.
- Step 4: The cost is n + k. Counting touches the n keys and reading back touches the k counters, so the work is n + k: 13 steps here. But k is the size of the key range. If the same eight keys could be anything up to 999 999, we would need a million counters, nearly all of them empty.
- Step 5: Radix: ones digit first. Radix sort handles big keys by sorting on one digit at a time, so each pass needs only ten buckets. Pass 1 uses the last digit. Each bucket keeps its numbers in arrival order: 53 came before 13, so it leaves first. A sort that keeps ties in order like this is called stable.
- Step 6: Then the tens digit. Pass 2 repeats the job on the tens digit, starting from the order pass 1 left. 13 and 17 share a bucket, and 13 leaves first only because pass 1 had already put it first. That is why each pass must be stable: it protects the work done on earlier digits.
- Step 7: When it pays. Radix sort costs d passes of n + k steps, where d is the number of digits and k the number of digit values. For a million 32-bit numbers that is about 4 million bucket drops, against roughly 20 million comparisons. The catch: keys must split into digits, and the buckets take extra memory.
Try it yourself
Learn this first
Spotted a mistake on this page?