Skip to content

Radix Sort ​

Radix sort does not compare numbers with each other. Instead, it sorts by distributing values digit by digit: first by the ones place, then the tens place, then the hundreds place.

At a Glance ​

  • Radix means the basic building block of data, that is, the base of a number system (0 ~ 9 for decimal). Radix sort uses these building blocks (digits) to sort.
  • As an analogy, it is like a post office that sorts letters into boxes 0 ~ 9 by the last digit of the postal code, gathers them back in box order, then sorts them into boxes again by the next digit to the left, and so on. Once every digit has been processed, the letters are in numerical order.
  • It is a non-comparison sort, which does not compare elements with each other.
  • It uses a stable counting sort for each digit, so the whole thing is also a stable sort.
  • It needs buffer (bucket) space to hold intermediate results, so it is not an in-place sort.

The Limit of Comparison Sorts ​

There are N! ways to order N elements. A comparison sort repeatedly asks yes/no questions like "is a < b?", so if you draw the questioning process as a tree (a decision tree) of height h, it has at most 2^h endpoints (leaf nodes).

  • To tell every case apart, there must be at least N! leaf nodes, so 2^h ≥ N! must hold.
  • Taking the log of both sides gives h ≥ log₂(N!), and log₂(N!) grows at the same rate as n log n (Θ(n log n)).
  • h is the number of comparisons in the worst case, which is the time complexity of a comparison sort. So no comparison sort can be faster than Ω(n log n) in the worst case.

The way to break through this O(n log n) wall is to not compare at all. Radix sort and counting sort are such methods.

Fixing Counting Sort's Weakness ​

  • Counting sort needs an array as large as the maximum value k of the input, so it becomes inefficient if even one large number is mixed in.
  • Radix sort improves on this by running counting sort one digit at a time. A single digit only takes values 0 ~ 9, so a count array of size 10 (maximum 9) is always enough.

How It Works ​

  1. Find the largest value to decide how many digits need to be checked.
  2. Run a stable counting sort based on the ones digit.
  3. Repeat step 2 for the tens digit, the hundreds digit, and so on, as many times as the maximum value has digits.
  4. Once the last digit is done, everything is sorted.

Example array [170, 45, 75, 90, 802, 24, 2, 66] (maximum 802 → 3 digits):

RoundDigitArray stateDescription
Start-[170, 45, 75, 90, 802, 24, 2, 66]Before sorting
1Ones[170, 90, 802, 2, 24, 45, 75, 66]Ordered by last digit 0, 0, 2, 2, 4, 5, 5, 6. When the last digits match, like 170 and 90, the original order is kept
2Tens[802, 2, 24, 45, 66, 170, 75, 90]802 and 2 have 0 in the tens place, so they go first. Their previous order (802 → 2) is kept
3Hundreds[2, 24, 45, 66, 75, 90, 170, 802]Those with 0 in the hundreds place come first, then 1 (170), then 8 (802). Sorting complete

In Pictures ​

The animation below distributes the numbers into ten boxes (buckets) by digit value (0 ~ 9), then takes them back out starting from box 0, repeating this for the ones, tens, and hundreds places in that order. In the figure, 个位, 十位, and 百位 mean the ones, tens, and hundreds place.

Radix sort distributing numbers into boxes by digit value and collecting them again

Image source: Wikimedia Commons (CC BY-SA 4.0, GnolizX)

Python Code ​

python
def counting_sort_by_digit(arr, exp):
    n = len(arr)
    buffer = [0] * n
    count = [0] * 10

    # 1. Count how many times each digit appears in the current place (exp)
    for i in range(n):
        count[(arr[i] // exp) % 10] += 1

    # 2. Convert to a running total → the last slot number for each digit
    for i in range(1, 10):
        count[i] += count[i - 1]

    # 3. Walk from the back and place each value (going from the back makes it stable)
    for i in range(n - 1, -1, -1):
        digit = (arr[i] // exp) % 10
        buffer[count[digit] - 1] = arr[i]
        count[digit] -= 1

    # 4. Copy the sorted result back into the original array
    for i in range(n):
        arr[i] = buffer[i]


def radix_sort(arr):
    if not arr:
        return
    # 5. Only loop as many times as the maximum value has digits
    m = max(arr)

    # 6. Sort by ones → tens → hundreds ... in that order (LSD)
    exp = 1
    while m // exp > 0:
        counting_sort_by_digit(arr, exp)
        exp *= 10


arr = [170, 45, 75, 90, 802, 24, 2, 66]
radix_sort(arr)
print(arr)
# Output: [2, 24, 45, 66, 75, 90, 170, 802]
  1. exp is 1, 10, 100, and so on. (arr[i] // exp) % 10 is the digit in the place currently being looked at. For example, for 802 with exp = 10, it is 80 % 10 = 0. The number of times each digit appears is counted in count.
  2. Turning count into a running total makes count[d] equal to "the number of elements whose digit is d or less," which is the last slot number for elements with digit d, plus 1.
  3. It walks the array from the back, puts each value into its slot in buffer, and decrements the slot number. Filling from the back keeps elements with the same digit in their original order (stable sort). This is the key to making radix sort work correctly.
  4. The buffer, now sorted by this digit, is copied back into the original array.
  5. It only needs to repeat as many times as the maximum value has digits.
  6. When m // exp becomes 0, every number is smaller than exp, so there are no more digits to look at. This code targets integers 0 or greater. If negative numbers are mixed in, you can split negatives and positives and sort them separately, or shift all values by the minimum so they are all 0 or greater and then sort.

Time and Space Complexity ​

CaseTime complexity
BestO(d × (n + b))
AverageO(d × (n + b))
WorstO(d × (n + b))
  • d is the number of digits in the numbers being sorted, and b is the radix (the base), which is 10 for decimal. It plays the role of k in counting sort, but it is fixed at b regardless of the maximum value. (Counting sort is O(n + k), which depends on the array's maximum value k.)
  • For each digit it counts n elements (n) and scans the count array (b), so one round is O(n + b), repeated d times. If d and b are small constants, it is effectively O(n).
  • Space complexity: O(n + b) extra memory. It needs a buffer (n) for intermediate results and a count array (b).

Pros and Cons ​

Pros ​

  • It does no comparisons, so with few digits it is faster than O(n log n).
  • It can sort not only integers but also data that can be split into "positions," such as strings (treating each character as one digit).
  • It is a stable sort.

Cons ​

  • Data without a notion of digits cannot be sorted directly. For example, floating-point numbers cannot be split straight into decimal digits, so extra work is needed to convert their bit representation into sortable integers.
  • It needs bucket (buffer) space to store intermediate results.

Interview Question: Why Sort from the Lowest Digit? ​

This question asks you to compare MSD (Most-Significant-Digit) and LSD (Least-Significant-Digit).

  • MSD: counting sort starting from the highest digit
  • LSD: counting sort starting from the lowest digit

In other words, both are possible. LSD works because each round is a stable sort. For values whose higher digits are equal, the order created in the earlier rounds (lower digits) is preserved, so once the last round finishes, everything is sorted.

ComparisonLSDMSD
Digits examinedEven when comparing 1600000 and 1, every digit position has to be checkedIf values already differ at a leading digit, there is no need to look at the last digit
Intermediate resultsYou cannot know the sorted result midway (e.g. the order of 10004 and 70002 is only decided in the last round)The order can be known midway from the important (leading) digits, which can save time
Extra costNoneNeeds a step to check whether each group is finished sorting, which uses more memory
ConsistencyThe algorithm is consistent (a Branch Free algorithm with no branching)Each group has to be handled differently, so it is not consistent
SpeedCan be somewhat faster when the number of digits is fixedBetter for data that splits early at the leading digits

That is why, when people say radix sort, they usually mean LSD.

Summary ​

ConceptPlain-language summary
Radix sortStarting from the last digit, distribute into boxes 0 ~ 9 and gather again, once per digit
Limit of comparison sortsComparing sizes alone can never be faster than n log n
LSDLowest digit first. Simple and consistent, so this is the usual choice
MSDHighest digit first. Can finish early when values differ at the leading digits
StabilityEach digit must use a stable sort so the order from earlier rounds is preserved