Sort one digit at a time.
Use stable digit passes and understand the restricted key model.
01 Model 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.
After a pass, values are ordered by all digit positions processed so far.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOR digit positions from least to most significant
distribute into digit buckets in existing order
concatenate buckets in digit order03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]
- 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 Count the cost
O(d(n + b)) for d digits and radix b
O(n + b) auxiliary for each bucket pass
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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]))06 Check your reasoning
Why must each digit pass be stable?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.