Radix Sort
Sort numbers digit by digit with a stable distribution per digit. LSD goes from the last digit to the first, MSD from the first to the last.
SolvesSorting
- best
- O(n)
- average
- O(d(n + b))
- worst
- O(d(n + b))
- space
- O(n + b)
A key with digits can be sorted by looking at one digit at a time. Each digit has only possible values, so counting sort or a bucket per digit can sort by it in .
One digit per key: a single distribution sorts everything, so there is one pass and n moves.
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
digit weight = 1
1def radix_sort(a):2 biggest = max(a)3 exp = 14 while biggest // exp > 0:5 # stable split by the digit at exp6 buckets = [[] for _ in range(10)]7 for x in a:8 digit = (x // exp) % 109 buckets[digit].append(x)10 a = []11 for bucket in buckets:12 for x in bucket:13 a.append(x)14 exp = exp * 1015 return aPass 1: sort by the digit worth 1.
- passes
- 1
- moves
- 0
How it works
LSD (least significant digit first) [1]:
- Distribute the keys into buckets by the last digit. Keep the order inside each bucket.
- Collect the buckets from 0 to 9.
- Repeat with the next digit, until the first digit is done.
This works because every pass is stable. After passes, the keys are sorted by their last digits. Equal digits keep the order given by the earlier passes.
MSD (most significant digit first): distribute by the first digit, then sort each bucket recursively by the next digit. A bucket with one key is done. So MSD may stop early.
Complexity
| Case | Input | LSD moves | MSD moves | Time |
|---|---|---|---|---|
| Best | one digit per key | |||
| Average | different keys | fewer | ||
| Worst | shared leading digits |
With digits of base , each pass costs . Total: . With a fixed key width, is a constant and the sort is linear in .
Implementations
- LSD: simple loop, always passes, needs a stable inner step.
- MSD: recursive. It handles keys of different length and stops when buckets hold one key. It needs more bookkeeping for small buckets.
Pitfalls
- LSD breaks if one pass is not stable. Appending to a bucket list keeps the order.
- MSD makes many tiny buckets. Production code switches to insertion sort for small ones.
- Negative numbers need an offset or a separate sign pass.
Related
References
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
Further reading
- D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
- K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.