How radix sort orders keys one digit at a time

Short answer: LSD radix sort stable-sorts fixed-width keys from the least significant digit to the most significant. Each digit is a counting sort on a radix-r alphabet. With d digits the time is Θ(d(n+r)). Sorting the least significant digit first is what makes a later digit pass keep the order of the earlier ones. MSD radix sort starts at the high digit and recurses, which fits variable-length strings.


What the problem actually asks

A machine word or a fixed-length string is a sequence of digits. If the digits are sorted from low to high by a stable sort, then after the highest digit is processed the keys stand in numeric order. A high digit decides the coarse order. A low digit decides the order inside one high digit, and the stable pass has already established that finer order.

The radix r is a free parameter. A byte digit uses r = 256 and d = 4 on a 32-bit word, or d = 8 on a 64-bit word. A wider digit shrinks d and grows the histogram.


What the algorithm guarantees

For nonnegative fixed-width keys, d passes of a stable counting sort produce a stable sort of the whole key. Time is Θ(d(n+r)) and extra memory is Θ(n+r). That is linear in n whenever d and r are treated as constants, which they are for a machine word and a byte digit. Signed integers need the sign bit mapped so that negative values sort before nonnegative ones, usually by flipping the sign bit and then running the unsigned procedure.

MSD radix sort partitions on the highest digit and recurses inside buckets whose digit matched. It can stop early on a bucket of length one, and it is the usual form for strings that do not share a common length. LSD is the usual form for integers, because every key has the same d and the passes are tight loops.


The working steps

  1. Choose a radix r = 2^b. A byte, b = 8 and r = 256, is the common choice for word-sized keys.
  2. For each digit position from least significant to most significant, run a stable counting sort on that digit.
  3. The counting sort reads digit (key >> shift) & (r−1), histograms r buckets, and writes records from the end of the current order.
  4. Increase the shift by b and repeat until the word is consumed.
  5. For signed integers, transform the sign bit so the unsigned digit order matches signed numeric order, then invert the transform if the bits must be restored. The sort itself only sees the transformed keys.

The procedure sorts keys that decompose into digits. It does not compare arbitrary objects, and it does not improve on comparison sorting when the key is a general string of unbounded length unless the MSD form is used and long shared prefixes are handled with care. Stability of the digit sort is a requirement, not an option.


Approaches that look simpler and fail

Approach Why it fails when a later digit pass must keep earlier order
Sort the most significant digit first with a full-array LSD schedule A later low-digit pass then reorders keys that a high digit had already separated, unless each pass is confined to one high-digit bucket. That confined schedule is MSD radix sort.
Use an unstable sort for the digit Equal digits lose the order computed by the less significant digits. The final order is then wrong inside those ties.
Pick r = 2 and call the cost the same as r = 256 Time is Θ(d(n+r)) with d = word length in bits divided by log₂ r. The product d(n+r) actually changes with the radix.
Run the unsigned passes on two’s-complement bits unchanged The sign bit makes negative numbers look larger than positive ones. They sort to the wrong end.

A single small integer range uses counting sort with no digit loop. Comparison sorting is what remains for keys that have no digit decomposition.


A working example

The Bash script and the Python script radix-sort nonnegative integers one decimal digit at a time, low digit first, with a stable counting pass per digit. Both print 2 24 45 66 75 90 170 802.

a=(170 45 75 90 802 24 2 66)
n=${#a[@]}
exp=1
max=${a[0]}
for v in "${a[@]}"; do if (( v > max )); then max=$v; fi; done
while (( max / exp > 0 )); do
  for ((d=0; d<10; d++)); do count[d]=0; done
  for ((i=0; i<n; i++)); do
    d=$(( (a[i] / exp) % 10 ))
    count[d]=$((count[d]+1))
  done
  for ((d=1; d<10; d++)); do count[d]=$((count[d]+count[d-1])); done
  for ((i=n-1; i>=0; i--)); do
    d=$(( (a[i] / exp) % 10 ))
    count[d]=$((count[d]-1))
    out[count[d]]=${a[i]}
  done
  for ((i=0; i<n; i++)); do a[i]=${out[i]}; done
  exp=$((exp*10))
done
echo "${a[*]}"
def counting_by_digit(a, exp):
    count = [0] * 10
    for v in a:
        count[(v // exp) % 10] += 1
    for d in range(1, 10):
        count[d] += count[d - 1]
    out = [0] * len(a)
    for i in range(len(a) - 1, -1, -1):
        d = (a[i] // exp) % 10
        count[d] -= 1
        out[count[d]] = a[i]
    return out

def radix_sort(a):
    exp = 1
    while max(a) // exp:
        a = counting_by_digit(a, exp)
        exp *= 10
    return a

a = radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
assert a == sorted([170, 45, 75, 90, 802, 24, 2, 66])
print(*a)

Where it is used

Radix sort orders fixed-length integers and strings one digit at a time, and the counting pass inside suffix-array construction is the same idea. Historical punched-card sorters were radix sorts. Comparison sorts take over when the key does not split into digits.


When you can drop this algorithm

Drop LSD radix sort for variable-length strings, where MSD recursion avoids padding every string to the longest length. Drop it when n is small enough that a well-tuned comparison sort wins on constants. Keep it for large arrays of fixed-width integers, with a stable counting sort on each digit from low to high.


Why this stays published

We publish this so a search for radix sort returns the low-to-high digit order and the reason the inner sort has to be stable. LSD radix sort stably sorts digits from low to high in Θ(d(n+r)) time, and that order is what makes the last pass agree with numeric order.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *