Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Sorting

Sorting Without Comparing.

Watch the explainer

Every comparison sort is stuck at O(n log n) — but if your keys are fixed-width integers, you can beat that by never comparing at all. Radix sort distributes numbers into 10 buckets by a single digit, gathers them back in bucket order, and repeats for the next digit up. The trick is the order: it must go least-significant digit first, and each pass must be stable. Step through the passes and watch a sorted array fall out with zero comparisons.

O(n · d) time · d = number of digits · stable, comparison-free
digit pass

One full round: bucket every number by one digit, then gather.

10 buckets

One per digit value 0–9. A number joins the bucket of its current digit.

stable gather

Numbers leave buckets in the exact order they entered — this preserves earlier passes.

LSD first

Least-significant digit first, working up to the most-significant.

radix.js — 10 buckets, one digit per pass
Ready
Eight numbers to sort. Each pass buckets them by one digit — starting at the units digit — then gathers bucket 0 through 9 in order. Step to distribute, step again to gather.
units
digit pass
–
phase
0
comparisons

How it works

Radix sort leans entirely on a stable counting pass per digit. Stability — numbers keep their relative order when their current digit ties — is what lets each pass preserve the work of every pass before it. Combined with going least-significant digit first, the final most-significant pass leaves the array fully sorted, because ties on the top digit are already broken by the lower digits sorted earlier.

1

Distribute by the current digit

Look at one digit of each number (units first) and drop the number into the matching bucket 0–9. Numbers with the same digit stack in arrival order.

2

Gather in bucket order

Concatenate bucket 0, then 1, … then 9, keeping each bucket’s internal order. The array is now sorted by that one digit — stably.

3

Move to the next digit up

Repeat on the tens digit, then hundreds, and so on. Because each pass is stable, the higher-digit pass keeps lower digits sorted among ties.

✓

Why least-significant first?

Sorting the most-significant digit first would let a later (lower-digit) pass scramble the top-level order. Going LSD-first with stable passes means the last, top-digit pass sees an array already sorted on everything below it.

Time
O(n · d)
Comparisons
0
Stable
Yes (required)
Beats
O(n log n)

The code

# LSD radix sort for non-negative integers, base 10 def radix_sort(a): if not a: return a max_d = len(str(max(a))) for d in range(max_d): # units, tens, hundreds, ... buckets = [[] for _ in range(10)] for x in a: digit = (x // 10**d) % 10 buckets[digit].append(x) # stable: arrival order kept a = [x for b in buckets for x in b] # gather 0..9 return a # sorted, zero comparisons

Quick check

1. What makes radix sort able to beat the O(n log n) comparison-sort bound?

2. Why must each digit pass be stable?

3. Why go least-significant digit first?

FAQ

What is radix sort?

A non-comparison sort for integers or fixed-width keys. It processes one digit at a time — bucketing numbers by that digit and gathering them back — repeating per digit. It runs in O(n·d) time, beating the O(n log n) comparison bound.

How does radix sort beat O(n log n)?

The O(n log n) bound is only for comparison sorts. Radix sort never compares elements — it buckets them by digit — so the bound doesn’t apply. Its time is O(n·d), effectively linear for fixed-width integer keys.

What is the difference between LSD and MSD radix sort?

LSD (least-significant digit) processes digits last-to-first with a stable pass each, simple and great for fixed-width keys. MSD (most-significant digit) goes first-to-last and recurses into buckets, handling variable-length keys and early stopping, but is more complex.

When should you not use radix sort?

When keys are long or unbounded (large d), can’t be broken into digits (arbitrary objects with a comparator), or bucket memory is tight. For general comparison sorting of arbitrary items, an O(n log n) sort like quicksort or mergesort is the better default.

The picture: four lists, one digit at a time

input17045759080224266 after pass 1: units17090802224457566 after pass 2: tens80222445661707590 after pass 3: hundreds22445667590170802
The page’s test input. Each pass is a stable sort on one digit, starting at the units. The last pass fixes the hundreds digit and the list is sorted, though no two numbers were ever compared.

Worked example, step by step

Sort [170, 45, 75, 90, 802, 24, 2, 66], the page’s test input, in base 10. The longest number has three digits, so there are three passes: units, tens, hundreds. A number with no digit at a position counts as 0 there (so 45 has hundreds digit 0). The table gives each number’s three digits and its position in the list after each pass.

ValueUnitsTensHundredsPos. after pass 1Pos. after pass 2Final pos.
170071167
45540643
75570775
90090286
802208318
24420532
2200421
66660854

Read the 170 and 90 rows. Both have units digit 0, so after pass 1 they sit next to each other in their original order (170 first): [170, 90, 802, 2, 24, 45, 75, 66]. Pass 2 then sorts by tens, and 170 (tens 7) stays ahead of 90 (tens 9), which is the right order for the last two digits. The pass that matters most is pass 3: 802 jumps from position 1 to 8 because its hundreds digit is 8, even though its lower digits (02) looked small. The two earlier passes are not wasted: where two numbers share a hundreds digit, they stay in the order the tens and units passes gave them. That is the stability the algorithm depends on, and the result is [2, 24, 45, 66, 75, 90, 170, 802].

Complexity and trade-offs

CaseTimeSpaceWhy
LSD radix sort, base 10O(n · d)O(n + 10)With 100,000 random keys below 1,000,000 (d = 6) the passes place 600,000 items in buckets, no comparisons.
Comparison sort (quicksort, mergesort, V8’s built-in)O(n log n)O(log n) to O(n)The same 100,000 keys took 1,529,318 comparisons in the built-in sort.
Radix with a larger baseO(n · d / log₂ b)O(n + b)Base 256 sorts 32-bit keys in 4 passes instead of 10 in base 10, at the cost of a 256-entry bucket array.
MSD radix sortO(n · d) worst, can stop earlyO(n + b) plus recursionHandles variable-length keys and can finish a bucket as soon as it has one item, but is harder to make stable and in place.
Counting sort aloneO(n + k)O(n + k)One pass, but memory grows with the key range k; radix is counting sort applied to small slices of the key.

The 600,000 against 1,529,318 comparison is not a fair race, since a bucket placement is cheaper than a comparison on some hardware and dearer on others, but it shows the shape: radix cost is set by the number of digits, comparison cost by the number of items. Radix wins when d is small and fixed (ids, timestamps, 32-bit integers) and loses when keys are long, since d then grows toward n. It also needs a second array of size n, so it is not an in-place sort, and it only works on keys that can be cut into digits.

Common mistakes

  • Letting a bucket reverse its items

    Each pass must keep arrival order within a bucket. If you pop from a stack, or gather buckets back-to-front, ties are reversed. Two passes on [25, 21] with reversed buckets return [25, 21] instead of [21, 25]: both share tens digit 2, and the second pass undid what the first had done.

  • Starting from the most significant digit

    Running the passes hundreds, then tens, then units sorts the input by its last digit and throws away the earlier work. The page’s test input comes out as [170, 90, 2, 802, 24, 45, 75, 66]. MSD radix sort exists, but it must recurse into each bucket, not run flat passes.

  • Using too few passes

    Hard-coding two passes sorts only by the last two digits. On [170, 45, 75, 90, 802, 24, 2, 66] that leaves [802, 2, 24, 45, 66, 170, 75, 90], with 802 before 170. Compute the pass count from the maximum: loop while max // exp > 0.

  • Feeding in negative numbers

    A digit extracted from a negative number is itself negative in C, Java and JavaScript (-5 % 10 is -5), which indexes outside the buckets. Python’s floor division avoids the crash, but a plain magnitude sort still places [3, −1, −5] as [3, −5, −1]. Split the negatives out, sort their absolute values, reverse, and put them before the rest; or offset every key by the minimum.

  • Using it on keys that are not fixed-width

    Strings of different lengths need padding, with the shortest sorting first, or MSD radix. Treating a missing character as the largest value rather than the smallest puts "ab" after "abc".

Where this shows up

  • Sorting integer ids and timestamps

    Fixed-width integer keys are the textbook case: 32-bit ids, 64-bit timestamps and similar fit four or eight passes of base 256, a handful of linear scans over the data.

  • Dotted addresses and dates

    An IPv4 address is four bytes and a date written as YYYYMMDD is a fixed-width number, so both sort with a few digit passes without parsing or comparing fields.

  • Fixed-length strings

    Equal-length strings such as postal codes, license plates or fixed-width DNA reads sort digit by digit from the last character to the first, which is radix sort over a larger alphabet.

  • Building other structures

    Suffix-array construction by prefix doubling sorts pairs of integer ranks on each round, and radix sort is the standard way to do that in linear time per round. It is also the second half of the “sort without comparing” family on this site, next to counting sort.

SOLVE IT YOURSELF

Solve it: sort without comparing

Every comparison sort is stuck at O(n log n). Radix sort never compares two numbers at all — it just buckets them by digit, least significant first. Python or TypeScript, running for real in your browser.

YOUR TASK

Implement radix_sort(nums) for non-negative integers: bucket by each digit position from least significant to most, and return the sorted list. No comparisons between values.

HINTS — 5 IDEAS
  1. Loop over digit positions using a multiplier exp = 1, 10, 100 … until max // exp is 0.
  2. For each pass, drop every value into one of 10 buckets keyed by (v // exp) % 10.
  3. Concatenate the buckets in order and use that as the input to the next pass.
  4. It only works because each pass is stable — appending preserves the previous pass’s ordering, which is what makes the more significant digit dominate.
  5. Least-significant-digit first is essential. Going most-significant-first with this simple scheme scrambles the earlier work.
CPython · WebAssembly

Keep going

▶  Watch it explained

Radix Sort: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextExternal Merge Sort: Bigger Than Memory Next on the “Beating n log n” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms