Algorithm Visualiser by Tsvetozar Biserov

Radix Sort

  • Ω( d(n + b) )
  • Θ( d(n + b) )
  • O( d(n + b) )
  • space O( n + b )

Radix sort orders numbers one decimal digit at a time, starting from the ones place and finishing with the highest digit. Each digit pass is a counting sort that keeps equal digits in their earlier order, so the work of earlier passes survives. The number of passes equals the number of digits in the largest value, which a single scan of the array finds first.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How radix sort works

Every value in 5, 2, 6, 1, 4, 3 has one digit, so the largest, 6, tells the loop that one pass is enough: exp = 1 runs, and exp = 10 fails the loop condition. In that pass the ones digits are tallied in ten cells, then turned into running totals, so each cell says how many elements have a digit no larger than its index. With all digits different, cells 1 to 6 read 1, 2, 3, 4, 5, 6 and cells 7 to 9 stay at 6.

The elements are then placed from the back of the array to the front: 3 goes to output slot 2, 4 to slot 3, 1 to slot 0, 6 to slot 5, 2 to slot 1 and 5 to slot 4. Walking backward while decrementing each cell is what keeps equal digits in their original order. The output buffer now holds 1, 2, 3, 4, 5, 6 and is copied into the real array, which is the only time the array itself is written.

That copy-back explains the trace table. It looks like the one for counting sort: 1, 2, 6, 1, 4, 3 after the first write, then no visible change at index 1, and so on until 1, 2, 3, 4, 5, 6, because each write replaces one slot while the old values further right still stand. The run costs 5 comparisons (all for the maximum), 18 reads and 6 writes on the array, and 36 reads and 27 writes on the buffers. A multi-digit input shows the real mechanism. For 21, 13, 25, 11 the ones pass gives 21, 11, 13, 25 and the tens pass gives 11, 13, 21, 25, where 21 stays ahead of 25 and 11 ahead of 13 only because the second pass is stable.

Radix Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Write 1 at index 0 1 2 6 1 4 3
2 Write 2 at index 1 1 2 6 1 4 3
3 Write 3 at index 2 1 2 3 1 4 3
4 Write 4 at index 3 1 2 3 4 4 3
5 Write 5 at index 4 1 2 3 4 5 3
6 Write 6 at index 5 1 2 3 4 5 6

All 6 changes are shown.

Pseudocode

max = largest value in a
for exp = 1, 10, 100, ... while max / exp >= 1
  count[0 .. 9] = 0
  for each x in a
    count[(x / exp) mod 10] += 1
  turn count into running totals
  for i = n - 1 down to 0
    d = (a[i] / exp) mod 10
    count[d] = count[d] - 1
    output[count[d]] = a[i]
  copy output back to a

Why these complexities

Each pass costs about n + b operations with b = 10: n reads to tally digits, 9 additions for the running totals, n placements and n copies back. The number of passes d is the digit count of the largest value, so the total is d(n + b), identical for best, average and worst. The order of the input never matters, only how many digits the maximum has.

That is linear when d is fixed, but d is not free. If n distinct values are sorted, they need at least about log₁₀ n digits, so d(n + b) ends up near n log n with a small constant and no comparisons. Radix sort pays off on large arrays of bounded integers, such as 32-bit keys processed in base 256, where d is 4. With base 10 and wide keys the passes pile up, and one huge outlier raises d for everybody, because the maximum decides how many passes run.

Space is n + b: a new output buffer of n elements and a table of ten counters are allocated for every pass, although a tuned implementation would reuse one pair. The sort is stable because placement goes backward through the input using running totals. It is not in place and not adaptive, and this implementation handles only non-negative integers.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 31 274 0
Already sorted 31 274 0
Reversed 31 274 0
Few distinct values 31 137 0

When to use it

Use it for integers or fixed-length keys with a bounded number of digits, such as IDs or timestamps, especially on large arrays. For keys with very many digits, a comparison sort may be faster.

Frequently asked questions

What does least significant digit first mean?

It starts with the ones digit and ends with the highest digit. Because every pass is stable, the final order is correct.

Why must each pass be stable?

A later pass must keep the order the earlier digits already gave to elements with the same current digit.

How many passes does it make?

One per decimal digit of the largest value, which is why the time is d(n + b) with d digits and base b.

Why base 10 here, and would another base be faster?

Base 10 keeps the digits readable. Any base works: a larger base means fewer passes but a bigger counter table in each one. Powers of two such as 256 let a computer extract digits with shifts and masks instead of division. The best base balances the number of passes against the table size and cache behaviour.

What does one extra digit in the largest value cost?

A complete extra pass over the whole array, even if a single element has that digit. The six-value trace takes one pass. Replace the 6 with 600 and the loop runs three passes, for ones, tens and hundreds, over all six elements. The maximum decides the pass count, not the typical value.

Background

The idea is older than computers. Punched-card sorting machines, descended from Herman Hollerith's tabulating machines of the 1880s, worked this way: sort the deck on one column at a time, starting with the last column, and after the final column the deck is in order. Knuth describes this least-significant-column-first method in section 5.2.5, Sorting by Distribution, as the way operators sorted cards.

As a computer program, radix sort appears in Harold Seward's 1954 MIT thesis alongside counting sort, and the pairing has stuck: the stable counting pass is the engine of each digit round. Variants that start from the most significant digit also exist and are common for strings of different lengths, but least significant first is the simpler choice for fixed-width integers, as here.

References

  • Knuth, The Art of Computer Programming, vol. 3, section 5.2.5 (Sorting by Distribution)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, section 8.3 (Radix sort)
  • Sedgewick, Wayne, Algorithms, 4th edition, section 5.1 (String Sorts)

Compare with

Algorithm Average time Worst time
Counting Sort Θ( n + k ) O( n + k )
Bucket Sort Θ( n + k ) O( n2 )
Big O notation
Best time Ω( d(n + b) ) good
Average time Θ( d(n + b) ) good
Worst time O( d(n + b) ) good
Worst space O( n + b ) fair

Properties

Stable
Yes
In place
No
Adaptive
No
Comparison-based
No