How do Counting Sort, Radix Sort, and Bucket Sort shatter the famous O(N log N) comparison-sorting speed limit—and why does scanning backward during placement preserve stability for multi-digit Radix Sort?


In 30 Seconds

Every comparison-based sort (Merge Sort, Quick Sort, Heap Sort) hits an information-theoretic lower bound of $\Omega(N \log N)$ because each a < b comparison yields at most 1 bit of information to distinguish $N!$ permutations. Counting Sort, Bucket Sort, and Radix Sort bypass pairwise comparisons completely by using the numeric values themselves as direct array indices—achieving O(N + K) linear time when value ranges or distributions allow.

The Real-World Analogy: Sorting 1,000 Exam Papers Graded 0 to 100

Suppose you need to sort 1,000 graded exams scored between 0 and 100:

  • Comparison Sort: You compare student exams against each other over ~10,000 comparisons.
  • Counting Sort: You lay out 101 labeled trays numbered 0 through 100 on a long table, walk through the stack once dropping each exam into its exact score tray, and collect the trays from 0 to 100! Total passes: 2 linear sweeps.

The Mathematical Invariant (Prefix Sums + Reverse Placement for Stability)

Why can't we just overwrite the array from count if we are sorting objects (like (score, student_name)) rather than raw integers?

  1. Prefix Sum Invariant: After converting frequency counts into cumulative prefix sums, count[x] stores the exact 1-based ending index of value x in the sorted output array!
  2. Backward Scan Stability Invariant: By iterating through the original input array from right to left (`N - 1` down to `0`), decrementing `count[x] -= 1`, and placing the element at `output[count[x]]`, the rightmost duplicate lands at the rightmost slot of its block—guaranteeing 100% stability!

Under the Hood: Memory Bandwidth, Radix Base-256 & Bucket Skew

  • Counting Sort Memory Trade-off: If $N = 5$ elements have values `[1, 100_000_000]`, allocating `count` of size $10^8$ wastes 800 MB of RAM and thrashes CPU caches ($O(N + K)$ explodes when $K \gg N$).
  • Radix Sort (Base-256 Byte Passes): Instead of base-10 digits (requiring slow integer division // 10 and modulo % 10), systems engineers sort 32-bit integers in 4 passes of 8 bits (base 256) using pure CPU bit shifts and masks: (num >> (8 * byte_idx)) & 0xFF!
  • Bucket Sort Clustering Trap: Bucket Sort divides `[min_val, max_val]` into $B$ uniform buckets and sorts each bucket with Insertion Sort. If inputs are uniformly distributed, each bucket holds $\approx N/B$ items ($O(N)$ expected time); if all inputs cluster into a single bucket, it degrades to $O(N^2)$!

Show Me The Code

# Day 18: Stable Counting Sort & Bucket Sort Implemented from Scratch in Python

def counting_sort_stable(arr):
    """
    Stable Counting Sort supporting negative integers via min_val offset.
    Time Complexity: O(N + K) | Space Complexity: O(N + K), where K = max - min + 1
    """
    if not arr:
        return []

    min_val, max_val = min(arr), max(arr)
    k = max_val - min_val + 1
    count = [0] * k

    # 1. Count frequencies
    for num in arr:
        count[num - min_val] += 1

    # 2. Convert counts into cumulative prefix sums (ending positions)
    for i in range(1, k):
        count[i] += count[i - 1]

    # 3. Traverse input BACKWARD to preserve stability
    output = [0] * len(arr)
    for i in range(len(arr) - 1, -1, -1):
        val = arr[i]
        idx = val - min_val
        count[idx] -= 1
        output[count[idx]] = val

    return output


def bucket_sort(arr, num_buckets=5):
    """
    Sorts floating-point or bounded numbers into uniform buckets + Insertion Sort.
    Average Time: O(N + K) | Worst Case (all in 1 bucket): O(N^2)
    """
    if len(arr) <= 1:
        return arr

    min_val, max_val = min(arr), max(arr)
    if min_val == max_val:
        return arr[:]

    buckets = [[] for _ in range(num_buckets)]
    span = (max_val - min_val) / num_buckets

    for num in arr:
        b_idx = int((num - min_val) / span)
        if b_idx == num_buckets:  # Handle max_val boundary
            b_idx -= 1
        buckets[b_idx].append(num)

    result = []
    for b in buckets:
        b.sort()  # Timsort / Insertion Sort on tiny bucket
        result.extend(b)
    return result


if __name__ == "__main__":
    print("Stable Counting Sort:", counting_sort_stable([4, -1, 2, -1, 0, 4]))
    print("Bucket Sort:         ", bucket_sort([0.42, 0.32, 0.23, 0.52, 0.25, 0.47]))

Dry Run (Tracing Stable Counting Sort on [4, 2, 2, 1])

PhaseActioncount Array (Indices 1..4)output Array
1. FrequencyCount occurrences of 1, 2, 3, 4[1, 2, 0, 1][0, 0, 0, 0]
2. Prefix SumAccumulate ending positions[1, 3, 3, 4][0, 0, 0, 0]
3. Reverse PlaceRead arr[3]=1 -> count[0] becomes 0[0, 3, 3, 4][1, 0, 0, 0]
4. Reverse PlaceRead arr[2]=2 -> count[1] becomes 2[0, 2, 3, 4][1, 0, 2, 0]
5. Reverse PlaceRead arr[1]=2 -> count[1] becomes 1[0, 1, 3, 4][1, 2, 2, 0]
6. Reverse PlaceRead arr[0]=4 -> count[3] becomes 3[0, 1, 3, 3][1, 2, 2, 4]

Speed & Memory

AlgorithmTime ComplexitySpace ComplexityStable?When to Choose
Counting SortO(N + K)O(N + K)YesInteger keys with small range $K = O(N)$ (ages, test scores, ASCII chars).
Radix Sort (LSD)O(d * (N + b))O(N + b)YesFixed-width 32/64-bit integers or fixed-length strings.
Bucket SortO(N + K) avg / O(N^2) worstO(N + K)YesUniformly distributed floating-point values in [0, 1).

Where You'll See It In Real Life

  1. GPU Parallel Sorting (NVIDIA CUB Radix Sort): Graphics cards sort millions of 3D triangles by depth every frame using parallel byte-wise Radix Sort because bit-mask distribution avoids branch divergence across GPU warps.
  2. Histogram & Image Equalization Engines: Photo editors compute 256-bin pixel brightness histograms using Counting Sort in a single pass.

Traps To Avoid

  • Trap 1: Using Counting Sort when $K = 10^9$ and $N = 100$. Fix: Always check that $K \le 10^6$; otherwise use comparison sorting or Radix Sort.
  • Trap 2: Iterating forward (`0` to `N-1`) during Counting Sort placement, which reverses equal keys and breaks Radix Sort! Fix: Always iterate backward (`N-1` down to `0`).

Practice

  1. Easy: Sort a string of lowercase English letters in O(N) time and O(1) space (26-slot frequency array).
  2. Medium: Given an array of integers, find the Maximum Gap between two successive elements in its sorted form in O(N) time and O(N) space (Pigeonhole Principle + Bucket Sort!).
  3. Hard: Implement 32-bit signed integer LSD Radix Sort in Python using 4 byte-wise passes (base 256) and sign-bit flipping (num ^ 0x80000000).

TL;DR

  • Counting, Radix, and Bucket Sort beat the $\Omega(N \log N)$ comparison barrier by using key values directly as array/bucket indices.
  • Prefix sums + backward traversal make Counting Sort stable—which is mandatory when used inside LSD Radix Sort.

References consulted: Baeldung Counting/Radix/Bucket Sort & DEV Linear-Time Sorting — referenced for verification — all content above is original.

Covered Log Update

Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort]