Sort one digit at a time.
Use stable digit passes and understand the restricted key model.
01 The idea
Least-significant-digit radix sort processes integer keys one digit position at a time. Each pass must preserve the previous order within equal current digits, so earlier digit information survives. With d digit positions and radix b, a bucket-based implementation uses work on the order of d(n + b). This example supports nonnegative integers; signed or textual keys need an additional deliberate representation policy.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def radix_sort(values):
result = list(values)
if any(type(value) is not int or value < 0 for value in result):
raise ValueError("Nonnegative integer keys required")
maximum, place = max(result, default=0), 1
while maximum // place:
buckets = [[] for _ in range(10)]
for value in result: buckets[(value // place) % 10].append(value)
result = [value for bucket in buckets for value in bucket]
place *= 10
return result
print(radix_sort([170, 45, 75, 90, 2, 24]))[2, 24, 45, 75, 90, 170]
03 Under the hood
- 1
The first pass groups by units, the next by tens, and so on. Zero and an empty list are handled by the maximum default and loop condition.
- 2
Appending to buckets in input order makes each pass stable. Flattening buckets in digit order establishes the next level of ordering.
- 3
Digit extraction and large-integer arithmetic have real costs. The key model and number of digits determine whether radix sorting is useful compared with built-in comparison sorting.
04 Your turn, builder
Check the algorithm with zeros and repeated values.
Reveal one possible solution +
def radix_sort(values):
result, place = list(values), 1
while max(result, default=0) // place:
buckets = [[] for _ in range(10)]
for value in result: buckets[value // place % 10].append(value)
result = [value for bucket in buckets for value in bucket]
place *= 10
return result
print(radix_sort([0, 10, 0, 2, 10]))05 Check your signal
Why must each digit pass be stable?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.