Radix sort
Sort the numbers digit by digit, starting from the ones digit, with a stable counting sort; after the last digit the whole array is sorted.
Radix sort sorts the numbers digit by digit, starting from the least significant digit (the ones). Each pass is a counting sort on that digit (only ten possible values: 0 to 9).
Read the full explanation ↓- Time:
O(d·(n + 10)) for d digits - Space:
O(n) - CLRS, section 8.3
- Horowitz–Sahni, chapter 7
Seven three-digit numbers: three passes for the ones, tens and hundreds digits.
def radix_sort(a):exp = 1while max(a) // exp > 0:a = sort_by_digit(a, exp)exp = exp * 10return adef sort_by_digit(a, exp):count = [0] * 10for x in a:d = (x // exp) % 10count[d] = count[d] + 1for d in range(1, 10):count[d] = count[d] + count[d - 1]out = [0] * len(a)for j in range(len(a) - 1, -1, -1):d = (a[j] // exp) % 10count[d] = count[d] - 1out[count[d]] = a[j]return out
Start
Local variables
Orange = changed in this step
a list
Call stack
- radix_sort()line 1
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- place
- current input (n=7)
Show as a table
| n | place |
|---|---|
| 4 | 12 |
| 6 | 18 |
| 8 | 24 |
| 10 | 30 |
| 12 | 36 |
| 14 | 42 |
| 16 | 48 |
Explanation
The idea
Radix sort sorts the numbers digit by digit, starting from the least significant digit (the ones). Each pass is a counting sort on that digit (only ten possible values: 0 to 9).
Why start with the ones?
The key is that every pass is stable. After the ones pass, the numbers are sorted by their ones digit. The tens pass sorts them by the tens digit, and because it is stable, numbers with equal tens digits keep their ones order. So after the tens pass the array is sorted by its last two digits, and so on up to the last digit.
Cost
For d digits: O(d·(n + 10)). When the number of digits is fixed, the time is linear, better than n log n.
What to watch in the trace
- Use the "every loop round" detail level to see only the end of each pass, and follow the order of the bars after each digit.
- On the "textbook-style example", after the ones pass the numbers are sorted by their last digit (720, 355, 436, …).