43: NON-COMPARISON SORTING — COUNTING, RADIX & BUCKET SORT

A student-friendly guide to linear-time sorting without pairwise comparisons—how Counting Sort, Radix Sort, and Bucket Sort work with 10 real-time examples and Python code.

💡 Summary: Breaking Past O(n log n) When Keys Have Structure

Comparison-based sorts (like Merge Sort, Quick Sort, and Heap Sort) decide order by comparing two elements at a time, which has a worst-case lower bound of Ω(n log n). When your keys are small integers, fixed-length codes/digits, or evenly spread numbers, you can place items using counts, digits, or range buckets instead of comparing every pair.

Counting Sort tallies occurrences over a bounded value range k, Radix Sort sorts digit-by-digit (using a stable sub-sort like counting sort), and Bucket Sort distributes values into ordered buckets and sorts each bucket.

1. Counting Sort, Radix Sort & Bucket Sort
Non-comparison sorts shine when input values follow a known structure or range, trading extra memory or range assumptions for linear-style speed:
  • Counting Sort: Counts how many times each value in 0..k appears, computes cumulative positions, and writes items in sorted order in O(n + k) time.
  • Radix Sort (LSD): Processes numbers or fixed-length strings one digit/character at a time from least significant to most significant using a stable sort each pass—taking O(d · (n + b)) where d is digit count and b is base (e.g., 10).
  • Bucket Sort: Splits a range (often [0, 1) or evenly spaced intervals) into buckets, sorts each small bucket, and concatenates them—often averaging O(n + k) when inputs are uniformly distributed.
Algorithm Typical Time Extra Space Best When
Counting Sort O(n + k) O(k) Non-negative integers in a small range k
Radix Sort (LSD) O(d · (n + b)) O(n + b) Integers or fixed-width codes with few digits d
Bucket Sort O(n + k) avg / O(n²) worst O(n + k) Values spread fairly evenly across range buckets
Python (non_comparison_sorts_demo.py)
def counting_sort(arr):
    if not arr:
        return []
    max_val = max(arr)
    count = [0] * (max_val + 1)
    for x in arr:
        count[x] += 1

    for i in range(1, len(count)):
        count[i] += count[i - 1]

    output = [0] * len(arr)
    for x in reversed(arr):  # Reverse scan preserves stability
        count[x] -= 1
        output[count[x]] = x
    return output

def _counting_sort_by_digit(arr, exp):
    n = len(arr)
    output = [0] * n
    count = [0] * 10

    for x in arr:
        digit = (x // exp) % 10
        count[digit] += 1

    for i in range(1, 10):
        count[i] += count[i - 1]

    for x in reversed(arr):
        digit = (x // exp) % 10
        count[digit] -= 1
        output[count[digit]] = x
    return output

def radix_sort_lsd(arr):
    if not arr:
        return []
    a = arr[:]
    max_num = max(a)
    exp = 1
    while max_num // exp > 0:
        a = _counting_sort_by_digit(a, exp)
        exp *= 10
    return a

def bucket_sort_unit(floats):
    if not floats:
        return []
    n = len(floats)
    buckets = [[] for _ in range(n)]
    for val in floats:
        idx = min(n - 1, max(0, int(val * n)))
        buckets[idx].append(val)

    result = []
    for b in buckets:
        result.extend(sorted(b))
    return result

print("Counting Sort:", counting_sort([4, 2, 2, 8, 3, 3, 1]))
print("Radix Sort   :", radix_sort_lsd([170, 45, 75, 90, 802, 24, 2, 66]))
print("Bucket Sort  :", bucket_sort_unit([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]))
Output: Counting Sort: [1, 2, 2, 3, 3, 4, 8] Radix Sort : [2, 24, 45, 66, 75, 90, 170, 802] Bucket Sort : [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
2. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-world scenarios where non-comparison sorting fits naturally:
  • 1. Sorting Exam Marks Out of 100 (Counting Sort): When 5,000 students have integer marks from 0 to 100, the value range k = 100 is tiny compared to n, making counting sort fast.
  • 2. Sorting Postal / PIN Codes or Fixed-Digit IDs (Radix Sort): Numeric codes with a fixed number of digits can be ordered cleanly pass by pass across digit positions.
  • 3. Bucketing Normalized Scores or Probabilities in [0, 1) (Bucket Sort): Grouping model confidence scores or normalized metrics into intervals from 0.0 to 1.0.
  • 4. Ordering Age or Rating Buckets in Analytics: Ages (e.g., 0..120) or star ratings (1..5) sit in small integer ranges suited for count-based grouping.
  • 5. Sorting Fixed-Width Batch / Serial Numbers: Codes with uniform length can be grouped by character position without full string comparisons on every step.
Python (realtime_non_comparison_1_to_5.py)
# 1. Sorting Student Exam Marks (0..100) Using Counting Sort
marks = [88, 72, 95, 88, 60, 72, 99, 81]
sorted_marks = counting_sort(marks)
print("1. Sorted marks (0..100):", sorted_marks)
Output: 1. Sorted marks (0..100): [60, 72, 72, 81, 88, 88, 95, 99]
3. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world examples showing where non-comparison sorts help—and when to be careful:
  • 6. Histogram & Frequency Distribution Buckets: Grouping latency values or response times into fixed time buckets (like 0–100ms, 100–200ms) for reporting.
  • 7. Sorting Large Integer IDs with Bounded Digit Width: When IDs are integers with a known maximum number of digits, radix sort avoids comparison overhead.
  • 8. Uniformly Distributed Sensor / Measurement Readings: Values spread evenly across a range can be placed into buckets for quick range-ordered output.
  • 9. Why Counting Sort Hurts When k Is Huge: If you have only 5 items with values like [1, 10_000_000], allocating a count array of size 10 million wastes huge memory.
  • 10. Why Non-Comparison Sorts Aren't Universal for Arbitrary Objects: General custom objects (like strings of varying lengths or complex structs) are often sorted more flexibly with comparison or key-based sorting.
Python (realtime_non_comparison_6_to_10.py)
# 6. Grouping API Response Latencies (ms) into 100ms Buckets
latencies_ms = [42, 185, 19, 310, 94, 240, 128, 67]

def bucket_latencies(values, width=100):
    buckets = {}
    for v in sorted(values):
        low = (v // width) * width
        label = f"{low}-{low + width - 1}ms"
        buckets.setdefault(label, []).append(v)
    return buckets

print("6. Latency buckets:", bucket_latencies(latencies_ms))
Output: 6. Latency buckets: {'0-99ms': [19, 42, 67, 94], '100-199ms': [128, 185], '200-299ms': [240], '300-399ms': [310]}
4. Exam & Lab Tips for Students
Keep these points in mind when answering theory or trace questions on non-comparison sorting:
  • Ω(n log n) applies to comparison-based sorting: Counting, radix, and bucket sorts beat n log n only by using extra assumptions about keys (such as small integer range or digit structure).
  • Stability in Radix Sort is crucial: LSD radix sort works only because each digit pass keeps ties in their relative order from the previous digit pass.
  • Check memory when k is large: Always compare k (value range) against n (number of elements) before choosing counting sort.
Python (non_comparison_checklist.py)
checklist = [
    "Counting Sort: O(n + k) time and space; best when range k is small.",
    "Radix Sort: Sorts digit by digit; requires a stable sub-sort.",
    "Bucket Sort: Distributes items into buckets; depends on data distribution."
]

for item in checklist:
    print("*", item)
Output: * Counting Sort: O(n + k) time and space; best when range k is small. * Radix Sort: Sorts digit by digit; requires a stable sub-sort. * Bucket Sort: Distributes items into buckets; depends on data distribution.
# Aspect Counting Sort Radix Sort (LSD) Bucket Sort
1 Core Sorting Idea Counts occurrences & places via prefix sums Sorts digit-by-digit with a stable pass Distributes into range buckets & sorts buckets
2 Time Complexity O(n + k) O(d · (n + b)) O(n + k) avg / O(n²) worst
3 Auxiliary Space O(n + k) O(n + b) O(n + k)
4 Key Type Fit Non-negative integers in small range k Integers / fixed-digit keys of length d Range-bounded / evenly spread numbers
5 Item Comparisons None (index/count placement) None across full keys Used when sorting inside each bucket
6 Stability Stable (with reverse fill pass) Stable (required for LSD order) Depends on bucket sort method
7 Large Range (k) Impact High memory cost if k >> n Scales with digit count d, not raw max Requires clean range-to-bucket mapping
8 Skewed Input Impact Low impact within range 0..k Low impact (fixed by digit count d) High impact if items clump in one bucket
9 Decimals / Negatives Needs offset/mapping for negatives Needs custom mapping for negatives/floats Fits [0, 1) floats easily with scaling
10 Best Use Case Marks (0..100), ratings, small integer ranges Fixed-width numeric codes/IDs Uniformly distributed floats/intervals