Data Structures · Sorting

Radix sort

Radix sort never compares two numbers. It sorts them one digit at a time, starting with the ones place, by dropping each number into one of ten buckets for that digit. After the last digit, the whole array is sorted. For many keys with few digits, that beats any comparison sort.

The idea

Think of sorting a stack of index cards numbered 0 to 999 by hand. You could deal them into ten piles by their last digit, stack the piles back up in order 0 to 9, then deal again by the middle digit, and finally by the first digit. After the third pass the cards are in order.

That is least significant digit (LSD) radix sort. Each pass:

  1. Distribute: look at one digit of every number and put the number in bucket 0 to 9 for that digit, keeping the numbers in the order they arrive.
  2. Collect: read the buckets back out, bucket 0 first, into the array.
  3. Move to the next digit (ones, tens, hundreds, …) until you have done as many passes as the largest number has digits.

Why does this work? Each pass must be stable: numbers with the same digit stay in the order the previous pass left them. In the example below, 2, 24, 45, 66, 75 and 90 all have hundreds digit 0. Because the hundreds pass is stable, they stay in the order the first two passes gave them, which is already sorted by their last two digits. In general, after pass k the array is sorted by its last k digits. If a pass were not stable, it would scramble the work of the earlier passes.

A worked example

Sorting {170, 45, 75, 90, 802, 24, 2, 66}. The largest value, 802, has three digits, so there are three passes. The highlighted digit is the one each pass sorts by. Short numbers are treated as if they had leading zeros: 45 is 045.

Counting sort: one pass in code

Real code does not build ten lists for every pass. It uses a counting sort on the current digit, which has the same effect with plain arrays:

  1. Count how many numbers have each digit: count[d].
  2. Prefix sums: add each count to the one before. Now count[d] is the position just past where the d-bucket ends in the output.
  3. Place each number into output[count[d] − 1] and decrease count[d]. Going through the array from the end puts later numbers further right in their bucket, which is what keeps the pass stable.
  4. Copy the output back into the array.

The lab below shows both views at once: the buckets as they fill, and the count[] values under each bucket.

Try it

The array and the buckets

1. Count2. Prefix sums3. Place (from the end)4. Copy back
arr
Buckets by digit, with count[d] below
output

Each bucket keeps numbers in arrival order, oldest at the bottom. Faded numbers have already been placed into output.

Variables

What is happening

main.cpp

    Radix sort written in the style of the class sorting code. The array in main() changes to match what you sort.

    How much work does it do?

    Let n be the number of keys, d the number of digits in the largest key, and b the base (10 here). Each pass does a counting sort that touches every key a few times plus every bucket once, so

    time = O(d · (n + b))    extra space = O(n + b)

    When d is small and fixed, that is linear in n. A comparison sort such as merge sort cannot do better than about n log₂ n comparisons, so radix sort wins when there are many keys with few digits: sorting a million 6-digit IDs takes 6 passes, while n log₂ n is about 20 million comparisons. When the keys are long (large d), the advantage shrinks or disappears.

    "Element writes" counts writes into output plus the copy back: 2 · n per pass. The last column is the approximate number of comparisons a good comparison sort needs.

    Strengths and weaknesses

    Strengths
    • No comparisons between keys at all.
    • Linear time, O(d · (n + b)), when keys have few digits.
    • Stable: equal keys keep their order.
    • Works for anything that breaks into fixed-size digits: IDs, dates, fixed-length strings.
    Weaknesses
    • Needs O(n + b) extra space for the output and counts.
    • Only works directly on non-negative integers or fixed-length keys; negative numbers and floating point need extra handling.
    • Slow when keys have many digits compared with log₂ n.
    • Not in place, and less cache-friendly than in-place sorts.

    Think first

    How many passes does radix sort make on {7, 512, 64, 3009}?

    Four, because the largest value, 3009, has four digits. Every number goes through all four passes, even 7.

    Why does countSort place numbers starting from the end of the array?

    Within a bucket, positions are handed out from right to left. Going from the end of the array means the last number with a given digit gets the rightmost position, so numbers with equal digits keep their order. That stability is what makes the earlier passes count.

    What would go wrong if you sorted by the most significant digit first, with the same method?

    The final pass, on the ones digit, would reorder everything by its last digit and destroy the order from the earlier passes. MSD radix sort exists, but it has to sort each bucket separately and recursively.

    Radix sort is O(n) for fixed d, and merge sort is O(n log n). Why isn't radix sort always used?

    It needs keys made of digits, extra memory, and enough keys for the passes to pay off. For long keys, d can be larger than log₂ n, and general-purpose comparison sorts work on any data that can be compared.