Radix Sort (LSD) visualization

Sort by the ones digit, then tens, then hundreds — each pass is a stable bucket sort.

Least-significant-digit radix sort distributes numbers into 10 buckets by the current digit, then collects buckets in order. Because each pass is stable, earlier digit orderings survive.

After d passes (d = number of digits) the array is sorted, giving O(d · (n + 10)).

Digits only make sense for non-negative numbers, so when the input has negatives we first shift everything by −min, sort, and shift back. (The alternative is to sort negatives and positives separately.)

Complexity

Time: best O(d·n), average O(d·n), worst O(d·n). Space: O(n + 10). Difficulty: Advanced.

Pseudocode

procedure radixSort(A):
  if min(A) < 0: shift ← −min(A); A ← A + shift
  for exp ← 1, 10, 100, … while max(A)/exp > 0:
    buckets ← 10 empty lists
    for x in A: buckets[(x / exp) mod 10].append(x)
    A ← concatenate buckets 0..9
  A ← A − shift

More sorting algorithms