/utils

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 dd digits can be sorted by looking at one digit at a time. Each digit has only bb possible values, so counting sort or a bucket per digit can sort by it in O(n+b)O(n + b).

One digit per key: a single distribution sorts everything, so there is one pass and n moves.

5031821394257647

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 a
1 / 18

Pass 1: sort by the digit worth 1.

passes
1
moves
0

How it works

LSD (least significant digit first) [1]:

  1. Distribute the keys into buckets by the last digit. Keep the order inside each bucket.
  2. Collect the buckets from 0 to 9.
  3. Repeat with the next digit, until the first digit is done.

This works because every pass is stable. After jj passes, the keys are sorted by their last jj 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

CaseInputLSD movesMSD movesTime
Bestone digit per keynnnnO(n)O(n)
Averagedifferent keysdndnfewerO(d(n+b))O(d(n+b))
Worstshared leading digitsdndndndnO(d(n+b))O(d(n+b))

With dd digits of base bb, each pass costs O(n+b)O(n + b). Total: O(d(n+b))O(d(n + b)). With a fixed key width, dd is a constant and the sort is linear in nn.

Implementations

  • LSD: simple loop, always dd 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

  1. 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.

Full bibliography