Skip to content
SimpleScope

Sorting · 19 / 19

Radix sort visualization

Radix sort sorts whole numbers one digit at a time, from the least significant digit up, using a stable counting sort for each digit.

Time: O(d (n + k)) in every case. Space: O(n + k). What Big-O notation means.

Last updated

About this lesson
Concept it teaches
Digit by digit; why stability matters
Canonical source
Cormen et al., Introduction to Algorithms, section 8.3
Builds on
Counting sort

I already know this: go to the check

See

+10 XP

Watch the real code run, one step at a time. Change the input and see what happens.

Predict first. Before you press Play, guess how many comparisons radix sort will make.

Run Radix sort

Comparisons
0
Writes
0
Step
1/122
  • Current
  • Swapped
  • Done

Array. index 0: 329; index 1: 457; index 2: 657; index 3: 839; index 4: 436; index 5: 720; index 6: 355.

Sort 7 numbers of up to 3 digits by one digit at a time, from the ones digit up to the digit in the 100s place. Each pass is a counting sort. It is stable, so a later pass never undoes the order an earlier pass made.

Sort 7 numbers of up to 3 digits by one digit at a time, from the ones digit up to the digit in the 100s place. Each pass is a counting sort. It is stable, so a later pass never undoes the order an earlier pass made.

Step 1/122comparisonwrite

With focus on the player: Space play · ← → step · Home End jump

Try your own input

Up to 16 whole numbers from 0 to 999, separated by commas or spaces. Radix sort here sorts 3 digit positions with a counting sort, so only whole numbers from 0 to 999 are accepted. A shorter number counts as having leading zeros.

The example from the textbook: three passes, from the ones digit up to the hundreds digit.

Curious how it compares? Race radix sort against another sort.

Understand

+15 XP

The idea in plain words: why it works, what it costs, when to use it. One question at the end.

Radix sort is a sorting algorithm for whole numbers that sorts them one digit at a time, starting with the least significant digit, using a stable counting sort for each digit. It never compares two numbers. This is the LSD (least significant digit first) version.

How it works

  1. Take the ones digit of every number and sort the numbers by it with counting sort, using the 10 possible digits as the range.
  2. Do the same with the tens digit, then the hundreds digit, until the digit positions are used up. Here that is 3 passes, for numbers up to 999.
  3. A number with fewer digits has 0 in the missing positions.

Time and space complexity

With d digit positions and k possible digit values (10 here), each pass is a counting sort that costs O(n + k). The d passes give O(d (n + k)), the same for every arrangement of the input.

Complexity
Best case timeO(d (n + k))
Average case timeO(d (n + k))
Worst case timeO(d (n + k))
Extra spaceO(n + k)
  • Time, best, average and worst: O(d (n + k)), where k is the number of digit values (10). The comparison count is always 0; the work is writes. For a fixed d it grows linearly with n.
  • Space: O(n + k): a count array of k cells and an output array of n cells, reused by every pass. It is not in place.

A worked example

Sort 170, 45, 75, 90, 802, 24, 2. The lesson always runs 3 passes, so 45 is read as 045 and 2 as 002. In each pass the table lists the digit of every number in the current order, and the array after the stable counting sort on that digit.

Digits and array order after each pass
PassDigit of each numberArray afterwards
Start170, 45, 75, 90, 802, 24, 2
1: ones0, 5, 5, 0, 2, 4, 2170, 90, 802, 2, 24, 45, 75
2: tens7, 9, 0, 0, 2, 4, 7802, 2, 24, 45, 170, 75, 90
3: hundreds8, 0, 0, 0, 1, 0, 02, 24, 45, 75, 90, 170, 802

Stability is visible in every pass. In pass 1, 170 and 90 both have the ones digit 0, and 170 stays in front because it was first. In pass 2, 170 and 75 both have the tens digit 7, and 170 stays in front of 75 because pass 1 had put it there. After pass 2 the array is ordered by its last two digits, and after pass 3 by all three. The run makes 0 comparisons and 141 writes: 47 for each of the 3 passes, the same count that counting sort makes on 7 values and k = 9.

Pseudocode

A holds n whole numbers of at most d digits. Each pass is the counting sort from the previous lesson, with the digit as the key, so k = 9. D and B have n cells and C has 10.

RADIX-SORT(A, d)
    place = 1
    for p = 1 to d
        for j = 0 to n - 1
            D[j] = floor(A[j] / place) mod 10
        let C[0..9] be zeros
        for j = 0 to n - 1
            C[D[j]] = C[D[j]] + 1
        for i = 1 to 9
            C[i] = C[i] + C[i - 1]
        for j = n - 1 downto 0
            C[D[j]] = C[D[j]] - 1
            B[C[D[j]]] = A[j]
        for i = 0 to n - 1
            A[i] = B[i]
        place = place * 10

The textbook version is shorter: for p from 1 to d, use a stable sort to sort A on digit p, with digit 1 as the lowest. The code above spells out that stable sort. The outer loop runs d times and each pass costs O(n + k).

Stability

Radix sort is stable, because each pass is stable. In fact it only works because of it: a pass that reversed equal digits would undo the order of the previous pass.

When to use it, and when not to

  • Use it for many integers or fixed-length keys with few digit positions: ids, zip codes, dates.
  • Avoid it on small arrays: three passes of counting cost more than a simple sort on a handful of values, as the race shows.
  • Avoid it when keys are long, because d grows with the key.

Where it is used

  • Card-sorting machines. Punched-card sorters could only look at one column at a time, so operators sorted a deck on the last column first and moved toward the first. CLRS and Knuth both trace radix sort back to these machines, and the order of the passes is the same as in this lesson.
  • Fixed-length keys. Dates sorted by day, then month, then year are the textbook example. Identifiers, zip codes and the four bytes of an IPv4 address work the same way: each position is a digit, and d is small and fixed.
  • Large arrays of machine integers. A 32-bit integer can be treated as 4 digits of 8 bits each, so k is 256 and d is 4. Four counting passes then sort the array in time proportional to n, with no comparison between values.

Variations and related ideas

This is the LSD version. The MSD version starts with the most significant digit and then sorts each group of equal digits on its own, which suits strings of different lengths but needs recursion. The digit does not have to be decimal: bytes (k = 256) mean fewer passes, at the cost of a larger count array. Each pass is a counting sort, and the counting sort vs radix sort page runs the two on the same inputs. For the comparison sorts, see merge sort vs radix sort and quick sort vs radix sort, and the Big-O guide for all the costs side by side.

One question to finish

In which order does the textbook radix sort process the digits?

Predict

+20 XP

The run stops and asks what happens next. The real run says if you were right.

Practice

+30 XP

Order the lines, fill in the gap, trace it by hand. The real run corrects every answer.

Check yourself

Four questions from memory. They also join your daily review. Questions return on a spaced schedule: right answers come back later, misses come back tomorrow.

Compare radix sort