Radix sort sorts keys one digit at a time instead of comparing whole keys. The common LSD (least significant digit) variant runs a stable counting sort on the ones digit, then the tens, then the hundreds, and so on; after the last digit the array is fully sorted. With d digits in base b it runs in O(d·(n + b)), which is linear for fixed-width keys such as 32-bit integers. It powers GPU sorting, suffix array construction and fast database sorts.
Think of it like
Punched-card sorting machines
Early 20th-century card sorters handled one column at a time: cards dropped into ten pockets by the digit punched in that column, and the operator stacked the pockets back in order and fed the deck through again for the next column. Starting with the rightmost column and working left, the deck came out fully sorted after one run per column. That is LSD radix sort, done by hand and machine decades before computers.
How LSD radix sort works
- 1
Count the digits
Find the maximum key to know how many digits
dthe longest key has in baseb(base 10 in the visualization). - 2
Distribute by the lowest digit
Stable-sort all keys by their least significant digit: drop each key into the bucket for that digit, in input order.
- 3
Collect
Concatenate buckets 0 through b − 1. The array is now sorted by its last digit.
- 4
Move one digit left
Repeat with the next digit (tens, hundreds, …). After pass
tthe array is sorted by its lasttdigits; after passdit is fully sorted.
| Pass | Digit | Array after the pass |
|---|---|---|
| start | [170, 45, 75, 90, 802, 24, 2, 66] | |
| 1 | ones | [170, 90, 802, 2, 24, 45, 75, 66] |
| 2 | tens | [802, 2, 24, 45, 66, 170, 75, 90] |
| 3 | hundreds | [2, 24, 45, 66, 75, 90, 170, 802] |
Why the digit sort must be stable
After pass t, the array is sorted by the last t digits. Pass t + 1 sorts by the next digit, and for keys that tie on that digit, the only thing that orders them correctly is the arrangement left by the earlier passes. A stable sub-sort keeps that arrangement; an unstable one throws it away.
Stable sub-sort
- Input
[25, 21]; ones pass gives[21, 25] - Tens pass: both have tens digit 2, a tie
- Stable keeps
[21, 25]: correct
Unstable sub-sort
- Same ones pass:
[21, 25] - Tens pass may swap the tied keys
- Result
[25, 21]: wrong
Complexity: O(d·(n + b))
For fixed-width keys (32-bit integers, 64-bit timestamps) d is a constant, so the sort is O(n). This does not contradict the Ω(n log n) bound for comparison sorts: radix sort never compares keys. There is also no free lunch: to have n distinct keys you need at least log₂ n bits, so for distinct keys the work is really proportional to the total number of key bits.
Choosing the base
A bigger base means fewer passes but a bigger count array. Base 10 is easy to follow but needs division; powers of two let you extract a digit with a shift and a mask. Base 256 (one byte per digit) is the sweet spot on most CPUs: 4 passes for 32-bit keys and a count array of 256 entries that sits in L1 cache.
| Base b | Digit size | Passes for 32-bit keys | Counters per pass |
|---|---|---|---|
| 2 | 1 bit | 32 | 2 |
| 10 | decimal digit | 10 | 10 |
| 16 | 4 bits | 8 | 16 |
| 256 | 8 bits | 4 | 256 |
| 2,048 | 11 bits | 3 | 2,048 |
| 65,536 | 16 bits | 2 | 65,536 (256 KiB, spills out of L1) |
MSD radix sort
MSD (most significant digit) radix sort goes the other way: partition all keys by their first digit into buckets, then recursively sort each bucket by the next digit. Buckets never need to be merged, since every key in bucket 3 is smaller than every key in bucket 4. A bucket with one key, or keys that are already distinguished, needs no further work.
LSD
- Iterative: exactly d passes over all n keys
- Needs fixed-length keys (or padding)
- Stable digit sort is mandatory
- Simple and branch-free: ideal for integers and GPUs
MSD
- Recursive: only distinguishing prefixes are examined
- Handles variable-length strings naturally
- Many tiny buckets: switch to insertion sort below a cutoff
- In-place variants exist (American flag sort); buckets can be sorted in parallel
Sorting strings
Strings are just keys whose digits are characters (base 256 for bytes, 26 for lowercase letters). For fixed-length strings such as license plates, YYYYMMDD dates, product codes or IP addresses, LSD from the last character to the first is simple and fast. For variable-length strings, MSD treats "end of string" as a character smaller than every real one, so "car" sorts before "cart".
def lsd_sort_fixed(strs: list[str], width: int) -> list[str]:
for d in range(width - 1, -1, -1): # rightmost character first
count = [0] * 257
for s in strs:
count[ord(s[d]) + 1] += 1
for r in range(256):
count[r + 1] += count[r] # count[r] = first slot for character r
out = [""] * len(strs)
for s in strs: # left to right with start slots: stable
out[count[ord(s[d])]] = s
count[ord(s[d])] += 1
strs = out
return strs
print(lsd_sort_fixed(["dab", "cab", "fad", "bad", "dad", "ebb", "ace"], 3))
# ['ace', 'bad', 'cab', 'dab', 'dad', 'ebb', 'fad']Handling negative numbers
Digit extraction assumes non-negative keys. In two's complement a negative number has its top bit set, so as an unsigned value it looks larger than every positive number. There are several fixes:
- Offset: subtract the minimum from every key (and add it back afterwards), so all keys are non-negative.
- Split: sort the negatives by absolute value, reverse them, and place them before the sorted non-negatives.
- Flip the sign bit: for 32-bit integers, sort by
x XOR 0x80000000as an unsigned value. This maps the most negative number to 0 and preserves order, so no extra pass is needed. It is the same as adding 2³¹. - Floats (IEEE 754): for negative floats flip all bits, for positive floats flip only the sign bit; the resulting unsigned integers sort in numeric order.
Where radix sort is used
- Suffix arrays: prefix doubling sorts pairs of ranks with radix sort for O(n log n) construction, and the DC3 (skew) algorithm reaches O(n) by radix-sorting triples of characters. See String Matching (KMP, Rabin-Karp, Z).
- GPU sorting: libraries such as NVIDIA CUB and Thrust radix-sort primitive keys, because each pass is a histogram plus a parallel prefix sum, operations that GPUs execute extremely well.
- Databases and analytics: engines such as DuckDB radix-sort normalized fixed-width keys to sort large tables quickly.
- Graphics and games: renderers sort draw calls by packed 64-bit keys (material, depth, layer) every frame.
- Networking and systems: sorting IP addresses, timestamps and other fixed-width identifiers.
Complexity
| Variant | Time | Space | Notes |
|---|---|---|---|
| LSD radix sort | O(d·(n + b)) | O(n + b) | d digits in base b; same in best, average and worst case |
| 32-bit integers, base 256 | O(n) | O(n) | 4 passes with 256 counters each |
| MSD radix sort (strings) | O(w·n) | O(n + d·b) | w = maximum key length; often far less, since only distinguishing prefixes are read |
Stable (LSD), not in-place, not comparison-based.
Implementation
Exactly what the visualization does: one stable counting-sort pass per decimal digit. For non-negative integers.
def radix_sort(a: list[int]) -> list[int]:
if not a:
return a
biggest = max(a)
exp = 1
while biggest // exp > 0: # one pass per decimal digit
count = [0] * 10
for x in a:
count[(x // exp) % 10] += 1
for d in range(1, 10):
count[d] += count[d - 1] # count[d] = keys with digit <= d
out = [0] * len(a)
for x in reversed(a): # right to left keeps it stable
d = (x // exp) % 10
count[d] -= 1
out[count[d]] = x
a[:] = out
exp *= 10
return aKey takeaways
- LSD radix sort runs a stable sort on each digit from least to most significant; after d passes the keys are fully sorted.
- Each pass is a counting sort, so the total cost is O(d·(n + b)): linear for fixed-width keys such as 32-bit integers.
- Stability of the per-digit sort is essential: ties on the current digit must keep the order set by the lower digits.
- Base 256 with shifts and masks is the usual practical choice; negatives are handled by flipping the sign bit.
- MSD radix sort recurses from the most significant digit, reads only distinguishing prefixes, and suits variable-length strings.
Common pitfalls
- Using an unstable sort for the digit passes, which scrambles the order established by earlier passes.
- Feeding negative integers to a digit extractor that assumes non-negative keys; negatives either crash or sort after positives.
- Overflowing the place value (
exp *= 10) in fixed-width integer languages when the maximum key has 10 digits. - Running LSD on variable-length strings without padding, or forgetting that "end of string" must sort before every character in MSD.
- Choosing a huge base (such as 2¹⁶) whose count array no longer fits in cache, making each pass slower than the passes it saves.
Interview tips
- Explain why radix sort can be linear: it is not a comparison sort, so the Ω(n log n) bound does not apply.
- State the complexity with all its parameters, O(d·(n + b)), and say what d and b are for the input at hand.
- When a problem demands O(n) sorting of bounded integers (such as Maximum Gap), radix sort or bucketing is usually the intended idea.
Real-world applications
- GPU sorting of keys and key-value pairs (CUB, Thrust).
- Suffix array construction (prefix doubling, DC3) for text indexing and bioinformatics.
- Database and analytics engines sorting normalized fixed-width keys.
- Sorting fixed-width identifiers: IP addresses, timestamps, packed render keys, postal codes.
Practice problems
Test yourself
Why must LSD radix sort use a stable sort for each digit?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.