Sub topic 8
Breaking Keys into Digits
Counting sort runs in O(n + k) time, where k is the size of the key range. That cost is fine when k is small. For 32-bit integers, k is about four billion, and a count array that large is not practical. Radix sort gets around this by never sorting on the whole key at once. It splits each key into small pieces called digits. Each digit has a small range, so counting sort can handle it cheaply.
This chapter covers that splitting step: what a digit is, how to pull digits out of an integer, how many digits a key has, and why ordering by digits gives the same result as ordering by value. The next chapter uses these pieces to build LSD radix sort.
This chapter assumes you can read Python, know Big-O notation, and are comfortable with binary numbers and the >> (shift) and & (mask) operators. It also assumes you have read the earlier chapter on stable counting sort.
Radix and Digits
The radix, or base, b is the number of distinct values a single digit can take. In base 10 a digit is one of 0 through 9. In base 2 a digit is 0 or 1. In base 256 a digit is one byte, from 0 through 255.
Any non-negative integer x can be written in base b as a sequence of digits:
x = c₀ + c₁·b + c₂·b² + … + c_{d−1}·b^{d−1}, with each 0 ≤ cᵢ < b.
Digit c₀ is the least significant digit and c_{d−1} is the most significant digit. For a fixed base, this representation is unique, apart from leading zeros.
This is the property radix sort depends on. Every digit lies in the range 0..b−1. So when you sort by one digit, counting sort's k is b−1, however large the whole key is.
Extracting Digits with Division
To get digit i of x in base b, divide by bⁱ to drop the lower digits, then take the remainder mod b to drop the higher ones:
def digit_at(x, i, b):
"""Return digit i (0 = least significant) of non-negative x in base b."""
return (x // b**i) % b
def digits_base(x, b, d):
"""Return the d base-b digits of non-negative x, least significant first."""
out = []
for _ in range(d):
out.append(x % b)
x //= b
return out
def num_digits(x, b):
"""Number of base-b digits needed to write non-negative x (0 needs one)."""
d = 1
while x >= b:
x //= b
d += 1
return d
print(digit_at(802, 0, 10), digit_at(802, 1, 10), digit_at(802, 2, 10)) # 2 0 8
print(digits_base(802, 10, 3)) # [2, 0, 8]
print(digits_base(802, 256, 2)) # [34, 3] since 802 = 3*256 + 34
print(num_digits(802, 10), num_digits(0, 10), num_digits(255, 256)) # 3 1 1digit_at works for one digit. digits_base peels off all digits in one pass and does not recompute b**i each time. When you sort, you usually need one digit position per pass across many keys, so the single-digit form is the one that ends up inside the sort loop.
Extracting Digits with Shifts and Masks
If b is a power of two, say b = 2ʳ, a digit is just a group of r bits. Division by bⁱ becomes a right shift by i·r bits, and mod b becomes a mask with the low r bits set:
def digit_bits(x, i, r):
"""Return digit i of non-negative x when each digit is r bits wide."""
mask = (1 << r) - 1
return (x >> (i * r)) & mask
x = 802 # binary 11_0010_0010, hex 0x322
print([digit_bits(x, i, 4) for i in range(3)]) # [2, 2, 3] -> hex digits 2, 2, 3
print([digit_bits(x, i, 8) for i in range(2)]) # [34, 3]
assert all(digit_bits(x, i, 8) == digit_at(x, i, 256) for i in range(4))On real hardware a shift and an AND each take a single cycle. Integer division takes many cycles. Because radix sort extracts one digit per element per pass, this difference shows up directly in running time. Production radix sorts almost always use a power-of-two radix, usually 8 or 11 or 16 bits, for this reason.
How Many Digits a Key Has
With r-bit digits and w-bit keys, the number of digits is d = ⌈w / r⌉. For keys bounded by a maximum value M, d is the number of base-b digits in M, which is ⌊log_b M⌋ + 1 for M ≥ 1.
The table shows the options for 32-bit unsigned keys:
| Digit width r (bits) | Radix b = 2ʳ | Digits d = ⌈32 / r⌉ | Count array size per pass |
|---|---|---|---|
| 1 | 2 | 32 | 2 |
| 4 | 16 | 8 | 16 |
| 8 | 256 | 4 | 256 |
| 11 | 2,048 | 3 | 2,048 |
| 16 | 65,536 | 2 | 65,536 |
| 32 | 4,294,967,296 | 1 | about 4 billion |
The last row is plain counting sort on the whole key. The first row is binary radix sort. Moving down the table trades more passes for a bigger count array per pass. A later chapter works out the cost of each choice. For now, notice that you can pick the digit width freely and that the choice moves you between two extremes.
There are two ways to choose d:
- Fixed width. Use the key type's width, for example 4 passes of 8 bits for a 32-bit integer. This is simple and predictable, but it wastes passes when every value is small.
- Data-driven. Compute the maximum key and stop once every remaining digit is zero. The loop
while (max_val >> shift) > 0does exactly this. One O(n) scan to find the maximum can save several full passes.
Python integers have no fixed width, so the data-driven approach is the natural fit there.
Why Digit Order Matches Numeric Order
Splitting a key into digits is useful only if ordering by digits gives the same result as ordering by value. Here is the claim:
For two non-negative integers written with the same number of base-b digits, comparing their digit sequences lexicographically, starting from the most significant digit, gives the same result as comparing the numbers.
The reason: suppose x and y first differ at position j, with xⱼ < yⱼ. All higher digits are equal, so they contribute the same amount to both. The digits below j contribute at most (b−1)(1 + b + … + b^{j−1}) = bʲ − 1 to x, and at least 0 to y. Digit j adds at least bʲ more to y than to x. So y − x ≥ bʲ − (bʲ − 1) = 1 > 0.
The "same number of digits" condition matters. Without leading zeros, 9 is [9] and 10 is [1, 0], and a lexicographic comparison puts 10 first. You can check both the claim and the failure case directly:
import random
def digits_base(x, b, d):
out = []
for _ in range(d):
out.append(x % b)
x //= b
return out
def num_digits(x, b):
d = 1
while x >= b:
x //= b
d += 1
return d
random.seed(1)
nums = [random.randrange(10**6) for _ in range(1000)]
d = num_digits(max(nums), 10)
# Padded to d digits, most significant first: matches numeric order.
by_digits = sorted(nums, key=lambda x: digits_base(x, 10, d)[::-1])
assert by_digits == sorted(nums)
# Unpadded: lexicographic order is wrong for integers.
unpadded = sorted([9, 10, 100, 2], key=lambda x: digits_base(x, 10, num_digits(x, 10))[::-1])
print(unpadded) # [10, 100, 2, 9]For integer keys, the shift-and-mask extraction pads for free, because a digit position above the number's highest set bit reads as 0. Strings work differently. "ab" should sort before "abc", which corresponds to padding on the right with a value smaller than every real character. A later chapter covers that case.
Keys That Are Already Digit Sequences
The same idea covers more than integers. Any key that is a fixed-length tuple of small integers, compared lexicographically, can be treated as a sequence of digits:
- Dates as (year, month, day). This is a mixed-radix key: each position has its own range, roughly 1..31 for day and 1..12 for month. Counting sort per position works with a different k at each position.
- IPv4 addresses, which are four bytes, or 4 digits in base 256.
- Multi-field records, such as sorting by (department, grade), where both fields are small enumerations.
In each case, the most significant position is the field you would compare first. Fields with small, known ranges suit this method well. A field like a 64-bit user ID is better split into several bit-digits of its own.
Common Mistakes
- Mixing digit conventions. Getting least-significant-first digits from one function and indexing them most-significant-first in another produces output that looks almost sorted. Pick one convention and keep it.
- Writing the mask as
1 << r. The mask is(1 << r) - 1. Without the subtraction, you test a single bit. - Forgetting operator precedence. In Python,
x >> s & mparses as(x >> s) & m, but in C&binds more loosely than comparisons. Always use parentheses. - Applying shifts to negative numbers. Python's
>>on negative integers shifts in ones (an arithmetic shift), and the digits you get do not sort in numeric order. Handle signs first, as a later chapter shows.
Exercise
Using 8-bit digits, list the digits of 100000 from least to most significant, and state how many passes a data-driven LSD radix sort would make on a list whose maximum is 100000.
Show answer
100000 = 1·65536 + 134·256 + 160, so the digits are [160, 134, 1]. The loop runs while (100000 >> shift) > 0, which holds for shift = 0, 8, and 16 and fails at 24 because 100000 < 2^24. That makes 3 passes.
Exercise
Why must keys share the same number of digits for lexicographic digit order to match numeric order? Give a counterexample in base 10 and explain why shift-and-mask extraction avoids the problem.
Show answer
Without padding, a shorter number can have a larger leading digit. For example, 9 is [9] and 10 is [1, 0], so lexicographic order puts 10 before 9. Shift-and-mask extraction reads every requested position, and positions above the number's highest bit come out as 0. Every key therefore gets the same number of digits, with leading zeros added automatically.
Exercise
For 64-bit unsigned keys, how many passes do 8-bit, 11-bit, and 16-bit digits need, and how large is the count array for each?
Show answer
d = ceil(64 / r). With 8 bits: 8 passes and 256 counters. With 11 bits: 6 passes, since 64/11 ≈ 5.8, and 2,048 counters. With 16 bits: 4 passes and 65,536 counters.