Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Radix sort and the least significant digit variant

Radix sorting rearranges records by examining one digit position at a time rather than comparing every pair of keys. In the least significant digit (LSD) method, a counting-sort pass distributes values into buckets for the units place, then repeats for tens, hundreds and higher positions. Because each pass preserves the order established by less significant digits, the final sequence is ordered by the complete number. The technique works especially well when keys have a known digit width and each digit has a small range.

This guide develops the bucket-distribution idea through pseudocode, complexity analysis and a Python implementation. It also marks the boundaries: radix sorting does not directly handle arbitrary Python objects, and a poorly chosen base can remove its performance advantage.

Approach Ordering strategy Typical time Extra space Main consideration
LSD radix sort Units digit through highest digit O(d(n + b)) O(n + b) Stable passes and a bounded base
MSD radix sort Highest digit through units digit Up to O(d(n + b)) O(n + b) May terminate before every digit is processed
Comparison sort Repeated key comparisons O(n log n) Varies General-purpose and supports arbitrary comparable keys
Shell sort Gap-based comparisons Gap-sequence dependent Usually O(1) In-place but generally not stable

How radix sorting works

The term radix refers to the numeric base used to represent a key, such as decimal 10 or binary 2. A decimal value such as 508 has a units digit of 8, a tens digit of 0 and a hundreds digit of 5. Instead of asking whether 508 is larger than another value, the algorithm gathers records with the same digit at the current position. Earlier passes then resolve ties among those records.

For the keys 170, 45, 75, 90, 802, 24, 2 and 66, the units pass produces the stable order 170, 90, 802, 2, 24, 45, 75, 66. The tens pass becomes 802, 2, 24, 45, 66, 170, 75, 90, and the hundreds pass finishes with 2, 24, 45, 66, 75, 90, 170, 802. Intermediate orders are not fully sorted, but each pass establishes another increasingly important part of the final order.

This differs from comparison-based methods such as heapsort, merge sort and quicksort, which learn the relative order of complete keys through comparisons. The shell sort performance review offers a useful contrast: shell sort still compares values, uses gap-based comparisons and is usually unstable, whereas LSD radix sorting uses stable digit distribution. A shell sort can be a strong general-purpose choice, but it does not exploit a bounded digit representation.

Inside the LSD radix sort

Write the base as b and the number of digit positions as d. For non-negative integer keys, the algorithm performs exactly d stable counting-sort passes. At place p, it extracts a digit with floor division and remainder, counts occurrences of each digit, calculates bucket boundaries and writes the records into an output array in their current order.

for place from 0 to d - 1:
    count every digit at place
    compute the starting position of each bucket
    write keys into output buckets in current order
    replace the working sequence with output

Stability is the crucial property. If two keys have the same units digit, the units pass must not swap them; their original order can determine their order at later positions. For example, 25 and 15 share a units digit. Keeping 25 before 15 in that pass lets the tens pass place 15 first. An unstable digit pass can therefore produce a badly ordered result even if its buckets are correct.

Negative integers and fractional values need extra handling. Python’s remainder operator produces a non-negative remainder for a positive divisor, so the simple extraction rule does not classify negative keys correctly. A known range can be shifted by a constant before sorting and shifted back afterwards, or negative and non-negative values can be processed separately. Strings and byte sequences are possible when their characters are converted into bounded digit codes. Fixed-width keys also need a declared width so that leading zeros are handled consistently.

Complexity and practical constraints

Each pass costs O(n + b): scanning the keys and writing them is O(n), while counting and locating the b buckets is O(b). With d passes, LSD radix sorting therefore takes O(d(n + b)) time and O(n + b) auxiliary space for counts and output. For a fixed base and fixed-width machine integers, this is linear in n; for long strings or large identifiers, d grows with the key length.

The base is a practical trade-off. Base 10 is intuitive, base 2 suits bit fields, and a byte-oriented process often uses 256 buckets. Larger bases reduce the number of passes but increase count-array overhead. A useful base is commonly comparable to, or no larger than, the number of records, but memory limits and the shape of the key matter more than a universal rule.

Radix sorting does not remove the work implied by key width. Sorting one million 64-bit identifiers and one million short numbers can have different costs, while a huge sparse numeric range can make a digit-wide bucket array wasteful. It also requires a stable sub-sort or a carefully preserved distribution order. For unrestricted keys, quicksort or mergesort may be simpler; for fixed numeric identifiers with enough memory, digit distribution operates outside the comparison model and is therefore not bound by its Omega(n log n) lower limit.

Python implementation and examples

The following Python version accepts non-negative integers, leaves the input untouched and uses the same positional rules for any supported base. It creates a fresh output sequence on every pass, making the stability requirement explicit.

def lsd_radix_sort(values: list[int], base: int = 10) -> list[int]:
    if base < 2:
        raise ValueError("base must be at least 2")
    if not values:
        return []
    if any(value < 0 for value in values):
        raise ValueError("non-negative integers only")

    largest = max(values)
    digit_count = 0
    while largest:
        digit_count += 1
        largest //= base
    digit_count = max(1, digit_count)

    working = values.copy()

    for place in range(digit_count):
        counts = [0] * base

        for value in working:
            digit = (value // (base ** place)) % base
            counts[digit] += 1

        next_position = 0
        for digit in range(base):
            amount = counts[digit]
            counts[digit] = next_position
            next_position += amount

        ordered = [0] * len(working)
        for value in working:
            digit = (value // (base ** place)) % base
            ordered[counts[digit]] = value
            counts[digit] += 1

        working = ordered

    return working

Calling the function with [170, 45, 75, 90, 802, 24, 2, 66] returns the ascending sequence shown earlier. A base of 2 processes binary positions, while base 16 groups hexadecimal digits. Because the code recalculates each bucket boundary before distributing records, equal digits retain their previous relative order.

Tests should cover an empty sequence, a single zero, repeated values, a value with several digits and a deliberately uneven bucket distribution. Property-based checks can generate random non-negative inputs, compare the result with Python’s sorted function and confirm that the original list was not modified. Readers who want broader language support can use the Python programming resources collection to compare this implementation with sorting APIs and related data-structure exercises.

Australian workloads and implementation checks

Australian use cases need not resemble hyperscale cloud traffic. A Sydney or Melbourne fulfilment centre may receive fixed-width SKU, invoice and order identifiers from marketplace sellers, while small retailers in Brisbane or Perth can receive similar exports without having a large engineering team. Everyday records offer less tidy examples: Woolworths or Coles receipts, EFTPOS timestamps and Opal taps in Sydney contain dates and locations, but those values need an appropriate integer representation. Four-digit Australian postcodes are another warning because numeric order does not create a geographic delivery route. Local context also raises governance duties. For covered organisations, the Commonwealth Privacy Act 1988 and the Australian Privacy Principles impose collection, use, security and disclosure obligations; sorting does not anonymise identifiable records. Customer segments used for email campaigns may also engage the Spam Act 2003, while pricing feeds supporting online offers must meet the accuracy requirements of the Australian Consumer Law. The community behind these tutorials describes its open educational approach on the about hello ML page.

A practical workload checklist identifies where the method is likely to fit:

Before implementation, check the constraints that determine whether the theoretical advantage survives: