5. Radix Sort

Sort without comparing — process one digit at a time

Every sorting algorithm we've seen so far — merge sort, quicksort — works by comparing pairs of elements. There's a proven lower bound: any comparison-based sort must do at least O(n log n) comparisons in the worst case. But what if we didn't compare at all?

Radix sort sidesteps comparisons entirely. Instead, it sorts numbers by processing them one digit at a time, from least significant to most significant (or vice versa). Each pass uses a stable sub-sort — typically counting sort — to group elements by a single digit. After processing every digit, the array is fully sorted.

The Core Idea

Radix sort in three lines

  1. Pick a digit position — start from the least significant digit (ones place).
  2. Stable sort by that digit — use counting sort to group elements by the current digit, preserving the relative order of equal-digit elements.
  3. Repeat — move to the next digit position until all digits have been processed.

The magic is in the stability. Because each pass preserves the order from previous passes, by the time you've processed the most significant digit, everything is sorted.

Counting Sort — The Building Block

Before we can run radix sort, we need a stable, non-comparison sort that works on a single digit. Counting sort is perfect: it counts how many times each digit value (0–9) appears, then uses those counts to place elements directly into their final positions.

  1. Count occurrences

    Create an array count[0..9]. For each element, extract the current digit and increment the corresponding count.

  2. Compute prefix sums

    Transform the count array so that count[d] holds the number of elements with digit ≤ d. This tells you where each digit group ends in the output.

  3. Place elements

    Walk the input array right to left (to maintain stability). For each element, use its digit to look up the position in the count array, place it in the output, and decrement the count.

Pseudocode (Counting Sort by Digit)

function counting_sort_by_digit(arr, exp):
    n = length(arr)
    output = new array[n]
    count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]   // digits 0-9

    // Count occurrences of each digit
    for i from 0 to n - 1:
        digit = (arr[i] / exp) % 10
        count[digit] += 1

    // Prefix sums — count[d] = number of elements with digit <= d
    for d from 1 to 9:
        count[d] += count[d - 1]

    // Build output (right to left for stability)
    for i from n - 1 down to 0:
        digit = (arr[i] / exp) % 10
        count[digit] -= 1
        output[count[digit]] = arr[i]

    // Copy back
    for i from 0 to n - 1:
        arr[i] = output[i]

A Simple Example

Sorting [170, 45, 75, 90, 802, 24, 2, 66]

Original:  [170, 45, 75, 90, 802, 24, 2, 66]

Pass 1 — ones digit (exp = 1): Extract digits: 0, 5, 5, 0, 2, 4, 2, 6 After stable sort by ones digit: [170, 90, 802, 2, 24, 45, 75, 66] ↑ ↑ ↑ 0s first 2s next then 4, 5s, 6

Pass 2 — tens digit (exp = 10): Extract digits: 7, 9, 0, 0, 2, 4, 7, 6 After stable sort by tens digit: [802, 2, 24, 45, 66, 170, 75, 90]

Pass 3 — hundreds digit (exp = 100): Extract digits: 8, 0, 0, 0, 0, 1, 0, 0 After stable sort by hundreds digit: [2, 24, 45, 66, 75, 90, 170, 802]

Result: [2, 24, 45, 66, 75, 90, 170, 802] ✓

Three passes — one per digit position — and the array is sorted. No element was ever compared to another. Each pass just looked at a single digit and placed elements into buckets.

Why Stability Matters

A stable sort preserves the relative order of elements with equal keys. This is absolutely critical for radix sort. When we sort by the tens digit, we need the ones-digit ordering to be preserved within each tens-digit group.

Stability in action

After pass 1 (ones digit):  [170, 90, 802, 2, 24, 45, 75, 66]

When pass 2 sorts by tens digit, 802 and 2 both have tens digit 0. Because the sub-sort is stable, 802 stays before 2 (their ones-digit order from pass 1 is preserved):

After pass 2: [802, 2, ...] ← 802 before 2, preserving pass 1 order

If the sub-sort were not stable, earlier passes would be wasted — elements that were correctly ordered by lower digits could get shuffled.

LSD vs MSD Radix Sort

There are two flavors of radix sort, named for which end of the number they start from:

Variant Direction How it works Properties
LSD (Least Significant Digit) Right to left Process digits from ones place upward; use a stable sort each pass Simple, naturally stable, processes all elements each pass
MSD (Most Significant Digit) Left to right Process from the highest digit; recursively sort each bucket Can short-circuit (stop early for some buckets), good for variable-length strings

LSD is the more common variant for integers and the one we focus on here. MSD is preferred for strings (like sorting words alphabetically) because it can stop early when a bucket has only one element.

Full Algorithm

Pseudocode (LSD Radix Sort)

function radix_sort(arr):
    max_val = maximum element in arr
    exp = 1   // start with ones digit

    while max_val / exp >= 1:
        counting_sort_by_digit(arr, exp)
        exp = exp * 10

That's it. Find the maximum value to know how many digits to process, then run counting sort once per digit position. The number of passes is d = ⌊log10(max)⌋ + 1.

Complexity Analysis

Time: O(d · (n + k))

Where d is the number of digits, n is the number of elements, and k is the range of each digit (10 for decimal). Each of the d passes runs counting sort in O(n + k) time.

For fixed-width integers (e.g., 32-bit), d is constant, making radix sort effectively O(n) — faster than any comparison-based sort.

Property Value
Time (all cases) O(d · (n + k))
Space O(n + k) — for the output array and count array
Stable? Yes (LSD variant)
In-place? No — requires O(n) auxiliary space
Comparison-based? No — bypasses the O(n log n) lower bound

Radix Sort vs Comparison Sorts

PropertyRadix SortQuicksortMerge Sort
Time O(d · n) O(n log n) avg O(n log n)
Worst case O(d · n) O(n²) O(n log n)
Space O(n + k) O(log n) O(n)
Stable? Yes No Yes
Works on Integers, fixed-width keys Any comparable type Any comparable type
Cache behavior Moderate (extra array) Excellent Good

Radix sort wins on paper when d is small relative to log n. For 32-bit integers with base-256 digits, d = 4, which beats log2(n) for any n > 16. In practice, the extra memory and cache pressure mean quicksort often wins for small arrays, but radix sort dominates when sorting millions of integers.

Choosing a Radix

We've been using base 10 for clarity, but real implementations often use a larger radix to reduce the number of passes:

Radix Digits per 32-bit int Buckets per pass Trade-off
10 10 passes 10 Easy to understand, many passes
256 (1 byte) 4 passes 256 Sweet spot for 32-bit integers
65536 (2 bytes) 2 passes 65,536 Fewest passes, but large count array; cache-unfriendly

Base 256 is the most popular choice in practice. Each "digit" is one byte, extracted with a bitwise AND and shift: digit = (value >> (8 * pass)) & 0xFF. Four passes sort any 32-bit integer.

Where Radix Sort Is Used

Application Details
Suffix array construction Building suffix arrays in O(n log n) or O(n) time relies on radix sort to sort suffixes by their first k characters
Database internals Sorting integer keys, timestamps, and fixed-width records in column stores
GPU sorting Radix sort maps naturally to parallel hardware — each pass is embarrassingly parallel
Network packet routing Sorting packets by IP address or port number — fixed-width integer keys
Counting sort for small ranges When keys are small integers (ages, grades, pixel values), a single counting sort pass suffices
Bioinformatics Sorting DNA k-mers (short fixed-length strings over a 4-letter alphabet)

Key Takeaways

  • Radix sort is a non-comparison sort that processes elements one digit at a time
  • It uses counting sort as a stable sub-routine for each digit position
  • LSD (least significant digit first) is the standard variant for integers
  • Stability is essential — without it, earlier passes would be undone by later ones
  • Time complexity is O(d · n) where d is the number of digits — effectively O(n) for fixed-width integers
  • It bypasses the O(n log n) lower bound for comparison sorts by not comparing at all
  • Real implementations use base 256 (one byte per digit) for just 4 passes over 32-bit integers
  • Radix sort excels when sorting large arrays of integers, but quicksort's cache locality wins for small or general-purpose workloads

Radix sort is a beautiful reminder that the rules we take for granted — like "sorting requires O(n log n) time" — are only rules within a specific model. Step outside comparison-based thinking and an entirely different, sometimes faster world opens up.