Data Structures · Sorting

Radix Sort (LSD)

🔢 The array a[] and buckets 0–9

element being processed (its digit is read)already in a bucketbucket being poured backthe underlined digit is the one being sorted on
result

🧾 Pass record

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The recipe: read the current digit → drop it in its bucket → pour buckets 0–9 back, repeat up to the most significant digit. Both steps must be stable.

📄 Key points

1Drop each element into buckets 0–9 by its current digit
2Pour the buckets back 0→9 (bucket order preserved)
3Digits run low to high: units → tens → hundreds …
4No comparisons: time O(d·(n+k)), space O(n+k), stable
Why does sorting the least significant digit first still work? Every pass is stable: the relative order of two elements can only change when their current digits differ, and elements with the same digit keep the order they already had — which is the order produced by the earlier (lower) passes. So after each pass the array is sorted by the last k digits, and after the most significant pass it is fully sorted.
Complexity: d passes (d = digits of the maximum), each scanning n elements and 10 buckets → O(d·(n + 10)), i.e. O(d·(n+k)). For small d and large n this beats the O(n log n) comparison sorts.
Space: the buckets need O(n + k). Stability: it is mandatory — an unstable pass would scramble the lower-digit order and produce a wrong result (the same link it shares with counting sort).
Limits: integers only (or keys that split into digits, like fixed-length strings or dates); floats and variable-length strings need extra work, and many digits mean too many passes, so comparison sorts win.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result