Beyond Comparison Sorts

Data Structures & Algorithms · Searching & Sorting · Advanced · 25 min

Know why comparison sorts are stuck at O(n log n), beat it with counting and radix sort, keep sorts stable, and find the k-th largest in O(n) average with quickselect.

A post office sorting letters. Instead of comparing two letters at a time, the clerk drops each letter straight into the pigeonhole for its postcode. No comparisons at all, just one pass.

The idea in everyday words

To sort exam papers by score out of 10, you would not compare papers in pairs. You would lay out 11 piles labelled 0 to 10 and drop each paper on its pile, then pick the piles up in order. That is counting sort. If scores went to 1,000, you could sort by the last digit, then the middle digit, then the first digit, keeping piles in order each time. That is radix sort.

Why comparison sorts cannot beat O(n log n)

Merge sort, quick sort and heap sort only ever ask one question: "is a < b?" Each answer is yes or no.

Think of the sort as a game of 20 questions. With 3 items there are 3! = 6 possible orders. Each yes/no question at best cuts the possibilities in half. After 2 questions you can tell apart only 4 cases, which is not enough. You need at least 3.

In general there are n! possible orders, so you need at least log₂(n!) questions, and log₂(n!) grows like n log n. That is a hard floor for any sort that only compares.

The escape: if you know more about the keys (they are small integers, or digits, or letters), you can use the key itself as an address and skip comparisons entirely.

Counting sort: use the value as an index

When every value is an integer in a small range 0..k-1:

  1. Count how many times each value appears.
  2. Prefix sums: turn counts into "how many items are ≤ v". That tells you where each value's block ends in the output.
  3. Place items walking the input right to left, putting each one at the end of its block and moving that end one slot left.

[2, 0, 2, 1] → counts [1, 1, 2] → prefix [1, 2, 4] → output [0, 1, 2, 2].

Counting sort
Time O(n + k)
Extra space O(n + k)
Good when k is not much bigger than n (ages, grades, ASCII letters)
Bad when values range up to a billion (k is huge)

Why walk right to left in step 3? So that equal values keep their original order. That property has a name.

Stability: equal keys keep their order

A sort is stable if items with equal keys come out in the same relative order they went in.

Sort [("Ann", 90), ("Bob", 85), ("Cat", 90)] by score. A stable sort gives Bob, Ann, Cat: Ann stays before Cat because she was before Cat in the input.

Why care? You can sort by several keys in passes: sort by name, then stably sort by grade, and students with the same grade stay alphabetical. Radix sort depends on this completely.

Stable Not stable (in the usual form)
Merge sort, insertion sort, counting sort, radix sort Quick sort, heap sort, selection sort
Python sorted / list.sort (Timsort) C's qsort
JavaScript Array.prototype.sort (required since ES2019)

Radix sort: one digit at a time

LSD radix sort (least significant digit first) sorts numbers by their last digit, then by the tens digit, then the hundreds, using a stable bucket pass each time.

[170, 45, 75, 90, 802, 24, 2, 66]

Pass Sort by Result
1 ones 170, 90, 802, 2, 24, 45, 75, 66
2 tens 802, 2, 24, 45, 66, 170, 75, 90
3 hundreds 2, 24, 45, 66, 75, 90, 170, 802

Why does it work? After pass 2, numbers are sorted by their last two digits. Pass 3 sorts by the hundreds digit, and because it is stable, numbers with the same hundreds digit keep the order from pass 2. So after the last pass they are sorted by all digits.

Cost: O(d · (n + b)) where d is the number of digits and b the base (10 here). For fixed-width keys like 32-bit integers or phone numbers, d is a constant, so it is linear.

Careful: this version only works for non-negative integers. With a negative number, x // exp % 10 puts it in the wrong bucket, and max(a) can be negative so the loop stops early: [3, -5, 12, -1] would come out as [3, 12, -5, -1]. The simple fix is an offset: subtract the smallest value from every number (now all are ≥ 0), radix sort, then add it back.

Quickselect: the k-th largest without sorting

"Find the 2nd largest" does not need the whole array sorted. Quickselect borrows quick sort's partition step:

  1. Pick a pivot and partition: smaller items to the left, then the pivot, then the rest. The pivot is now in its final sorted position p.
  2. The k-th largest lives at index target = n - k of the sorted array.
  3. If p == target, done. Otherwise keep only the side that contains target and repeat.

Quick sort recurses into both sides. Quickselect throws one side away, so on average the work is n + n/2 + n/4 + ... ≈ 2n = O(n).

Method Time
sort, then index O(n log n)
min-heap of size k O(n log k)
quickselect O(n) average, O(n²) worst

The worst case happens with consistently bad pivots (always the smallest or the largest). A fixed first or last pivot has inputs that do exactly that: sorted input for the classic two-way partition, reverse-sorted input for a three-way one. A random or middle pivot makes that very unlikely.

Watch out for duplicates. The usual two-way partition ("smaller go left") does badly when many values are equal to the pivot: on [7, 7, 7, ...] nothing is smaller, the pivot lands at the edge, and each round removes just one item. That is O(n²) every time, not bad luck. The fix is a three-way partition (the "Dutch national flag" idea): split the range into smaller | equal | bigger. If the target index falls inside the equal band, the pivot is the answer, so all the duplicates are handled in one pass.

There is a guaranteed O(n) method (median of medians), but in practice people use quickselect or a heap.

Step by step

  1. Setup:

    nums = [3, 2, 1, 5, 6, 4], k = 2. The 2nd largest sits at index target = 6 - 2 = 4 of the sorted array. Range lo = 0, hi = 5.

  2. Round 1:

    Pivot = the middle value, a[2] = 1. Split into smaller | equal | bigger: nothing is smaller, so the equal band is just index 0 and the rest is bigger: [1, 2, 5, 6, 4, 3]. Target 4 is past the band, so keep only the bigger part: lo = 1.

  3. Round 2:

    Range [1..5] holds 2, 5, 6, 4, 3. Pivot = the middle one, 6. Everything else is smaller, so 6 lands at index 5: [1, 2, 5, 4, 3, 6]. Target 4 is before the band, so hi = 4.

  4. Round 3:

    Range [1..4] holds 2, 5, 4, 3. Pivot = 5. The smaller values 2, 4, 3 fill indices 1 to 3 and 5 lands at index 4: [1, 2, 4, 3, 5, 6]. The equal band is index 4, which is the target.

  5. Found:

    a[4] = 5 is the 2nd largest. Each round kept only one side. With [7, 7, 7, 7] the very first round would put every 7 in the equal band and finish at once.

Code example

def counting_sort(a, k):              # values in 0..k-1
    count = [0] * k
    for x in a:
        count[x] += 1
    for v in range(1, k):
        count[v] += count[v - 1]        # count[v] = how many items <= v
    out = [0] * len(a)
    for x in reversed(a):               # right to left keeps it stable
        count[x] -= 1
        out[count[x]] = x
    return out

def radix_sort(a):                      # non-negative integers only
    exp = 1
    while a and max(a) // exp > 0:
        buckets = [[] for _ in range(10)]
        for x in a:
            buckets[(x // exp) % 10].append(x)   # stable: keeps arrival order
        a = [x for b in buckets for x in b]
        print("  after digit", exp, a)
        exp *= 10
    return a

def quickselect(a, k):                  # k-th largest, a is modified
    target, lo, hi = len(a) - k, 0, len(a) - 1
    while True:
        pivot = a[(lo + hi) // 2]       # middle pivot: sorted input stays fast
        lt, i, gt = lo, lo, hi          # smaller | equal | bigger
        while i <= gt:
            if a[i] < pivot:
                a[lt], a[i] = a[i], a[lt]
                lt, i = lt + 1, i + 1
            elif a[i] > pivot:
                a[i], a[gt] = a[gt], a[i]
                gt -= 1
            else:
                i += 1
        if target < lt:
            hi = lt - 1
        elif target > gt:
            lo = gt + 1
        else:
            return pivot                # target is in the equal band

print("counting:", counting_sort([2, 0, 2, 1, 3, 0], 4))
print("radix:")
print("  result", radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))
print("2nd largest:", quickselect([3, 2, 1, 5, 6, 4], 2))
print("many duplicates:", quickselect([7] * 100000, 500))
people = [("Ann", 90), ("Bob", 85), ("Cat", 90)]
print("stable by score:", sorted(people, key=lambda p: p[1]))

Complexity

  • Time: Quickselect: O(n) on average (n + n/2 + n/4 + ...) with a three-way partition, even with many duplicates; O(n²) worst case with very unlucky pivots. Counting sort: O(n + k). Radix sort: O(d · (n + b)) for d digits in base b
  • Space: Quickselect: O(1) extra in place (O(n) here because we copy the input). Counting sort: O(n + k). Radix sort: O(n + b) for the buckets

Interview tips

  • For 'k-th largest', give three answers in order: sort (n log n), a min-heap of size k (n log k, great for streams), quickselect (O(n) average). Then discuss trade-offs.

  • If asked 'can you sort faster than n log n?', say: not with comparisons alone (decision-tree argument), but yes with counting or radix sort when keys are small integers.

  • Mention pivot choice for quickselect: a random or middle pivot avoids the O(n²) case on sorted input. Then mention duplicates: a three-way partition keeps [7, 7, 7, ...] linear too.

  • Know which sorts are stable, and give a reason it matters: multi-key sorting and radix sort.

  • Sort Colors (Dutch national flag) is a favourite: counting sort works, and a one-pass three-pointer partition is the expected follow-up.

Challenge: K-th Largest with Quickselect

Return the k-th largest value in nums (k = 1 is the maximum). Duplicates count separately: in [5, 5, 4] the 2nd largest is 5.

Do it in O(n) average time with quickselect, without sorting. The tests include big inputs: a sorted list, a reverse-sorted list, a list where every value is the same, and numbers that are very far apart. So pick a middle (or random) pivot, handle duplicates well, and compare values instead of counting them.

Example: kth_largest([3, 2, 1, 5, 6, 4], 2) → 5

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Searching & Sorting

Previous: Sorting: Bubble, Merge & Quick · Next: Backtracking