How least-significant-digit radix sort works
For example, after the units pass, values are ordered by units. A stable tens pass orders by tens while preserving units order among ties. Repeating through the highest digit produces the full numeric order. The visualizer lets you step through each pass and inspect how the ordering accumulates.
Try it yourself: Radix Sort
Step through the units pass, then the tens pass. Check that the array is ordered by the digits processed so far, and that equal-digit values retain their previous order.
Why stability matters
After the units pass, 21 comes before 22 because its units digit is smaller. Both have tens digit 2, so a stable tens pass keeps 21 before 22. If it reordered equal-digit values arbitrarily, it could destroy the earlier ordering.
If a pass reorders equal-digit values arbitrarily, it can undo the ordering established by less significant digits. Stability lets each new pass refine the previous result.
Cost and limits
With n keys, d digit positions, and digit base k, counting-based passes take O(d(n + k)) time and typically O(n + k) extra space. For fixed-width keys and a fixed base, d is bounded, so runtime grows linearly with the number of keys.
That does not contradict the Ω(n log n) lower bound for comparison sorting: radix sort uses the representation of the keys instead of learning their order only through comparisons. It is useful for large batches of fixed-format integers, strings, or identifiers when the number of passes and extra memory are reasonable. It is a poor fit for arbitrary objects or keys with costly, unbounded representations.
Choose a base
For a 32-bit nonnegative integer, base 256 processes one byte per pass, so it needs four digit passes and a 256-entry count array. A larger base reduces the number of passes but uses a larger count array. Practical performance also depends on memory traffic, implementation, and hardware; the asymptotic bound alone does not guarantee it will beat a comparison sort.