Sub topic 8
Breaking Keys into Digits
This chapter assumes you know how stable counting sort works, how integers are stored in binary, and how Python's >> (right shift) and & (bitwise AND) operators behave.
Counting sort costs O(n + k), so it only works well when the key range k is small. A 32-bit key has about 4 billion possible values, which is far too many for one count array. The fix is to split each key into small pieces called digits, where each digit has a small range. Counting sort can then handle one digit at a time.
Digits and Radix
A radix, or base, b is the number of possible values one digit can take. In base 10 each digit is between 0 and 9. Any non-negative integer x can be written as
x = d₀ + d₁·b + d₂·b² + … + d₍d−1₎·b^(d−1)
where every dᵢ is between 0 and b − 1. Digit d₀ is the least significant digit and d₍d−1₎ is the most significant digit.
The base you choose decides how a key splits up. Here is the key 802 in three bases:
| Base b | Digits (least significant first) | Number of digits d |
|---|---|---|
| 10 | 2, 0, 8 | 3 |
| 16 | 2, 2, 3 | 3 |
| 256 | 34, 3 | 2 |
Extracting a Digit
For any base, digit i is (x // b**i) % b. When b is a power of two, b = 2^r, division turns into a right shift and the remainder turns into a mask. Both are cheap operations for the CPU.
def digit_any_base(x, i, b):
"""Digit i of non-negative x in base b (digit 0 is least significant)."""
return (x // b**i) % b
def digit_pow2(x, i, bits):
"""Digit i of x when the base is 2**bits."""
mask = (1 << bits) - 1
return (x >> (i * bits)) & mask
def num_digits(max_val, bits):
"""Number of base-2**bits digits needed to represent max_val."""
d = 0
while (max_val >> (d * bits)) > 0:
d += 1
return max(d, 1)
x = 802
print([digit_any_base(x, i, 10) for i in range(3)]) # [2, 0, 8]
print([digit_pow2(x, i, 4) for i in range(3)]) # [2, 2, 3]
print([digit_pow2(x, i, 8) for i in range(2)]) # [34, 3]
print(num_digits(802, 8)) # 2The Trade-off in Choosing b
With r bits per digit, a w-bit key splits into d = ⌈w / r⌉ digits, and each digit has b = 2^r possible values. A larger base means fewer digits, and each digit needs a larger count array. For 32-bit keys:
| Bits per digit r | Base b | Digits d | Count array size |
|---|---|---|---|
| 1 | 2 | 32 | 2 |
| 4 | 16 | 8 | 16 |
| 8 | 256 | 4 | 256 |
| 16 | 65,536 | 2 | 65,536 |
Every digit has a small range, so counting sort can sort on it cheaply. A later chapter puts these numbers into a cost formula and shows how to pick r.
Common Errors
- Off-by-one digit count. If you compute d from
max_val.bit_length() // bitswithout rounding up, you miss the top digit. The loop innum_digitsavoids this, and it returns 1 for an all-zero input. - Forgetting the mask.
x >> (i * bits)by itself still contains every higher digit. You have to apply& maskto keep only digit i. - Mixing up digit order. Index 0 must always mean the least significant digit. Radix sort's correctness depends on processing the digits in a defined order.
- Negative keys. In Python, right-shifting a negative number keeps its sign, so the masked digits no longer match the key's order. A later chapter covers how to handle signed keys.
Exercise
Using 4-bit digits, list the digits of 0xBEEF least significant first. How many digits does a 20-bit maximum key need with 8-bit digits?
Show answer
The digits are 0xF, 0xE, 0xE, 0xB, which is 15, 14, 14, 11. A 20-bit key with 8-bit digits needs ⌈20 / 8⌉ = 3 digits.
Exercise
Why is the base usually a power of two instead of 10 when you sort machine integers?
Show answer
With a power-of-two base, digit extraction is a shift plus a mask, which are single cheap instructions. Base 10 needs integer division and modulo, which are slower, and the digits don't line up with the key's binary layout.