Radix sort

Digit by digit · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Radix sort

Counting sort is no good if the range is huge, like 8-digit student IDs: 100 million counters would be needed. Radix sort uses the same idea, but one digit at a time. It sorts all the numbers by the units digit with counting sort, then by the tens, then by the hundreds, and so on. Since each digit goes from 0 to 9, each pass uses only 10 counters.

To trace it by hand with [32, 15, 21]: by units, 2, 5 and 1, you get [21, 32, 15]. By tens, 2, 3 and 1, you get [15, 21, 32]. Done: 2 passes for 2-digit numbers. In the 2nd pass, if 2 numbers had the same tens digit, they'd keep the order from the 1st, which already sorted them by units.

To get digit k of a number x in base 10, you divide by 10 to the power k − 1, round down and take the remainder of dividing by 10. For example, digit 2 of 4,735: 4,735 / 10 = 473.5, rounded down 473, and 473 % 10 = 3. That calculation tells counting sort which counter each number goes into on each pass.

Radix sort starts with the least significant digit, the units, and ends with the most significant. That way, the last pass sorts by what matters most, and the earlier ones, since each pass is stable, remain as tie-breakers. If it started with the most significant, the following pass by units would break the order achieved by the hundreds.

With n numbers of up to k digits in base d, each counting sort pass costs O(n + d), and there are k passes: O((n + d) × k). With base 10 and few digits, it's almost O(nk), and if k is small, close to O(n). It uses O(n + d) memory: the result array and the d counters. It's stable if each pass is.

Radix sort handles much bigger ranges than counting sort, but with one condition: the data has to be writable with a fixed, not very large, number of digits. It works well with student IDs, phone numbers or dates. With floating-point numbers it doesn't work directly, because their number of digits can be huge and there's no simple way to split them into digits.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Digit by digit