TExcelTAD
Home › Data Structures & Algorithms › Fast Sorts: Complexity

Fast Sorts: Complexity

Quick sort and merge sort break the O(n²) barrier with divide and conquer, reaching O(n log n). Counting sort and radix sort go even further, to linear time, by not comparing values at all. This lesson explains where those bounds come from and when each one applies.

Why divide and conquer gives n log n

Merge sort splits n values in half again and again until single values remain. That takes log₂ n levels. At every level, the merges together process all n values once:

text
level 0:  [ 8 values ]                    8 values merged
level 1:  [ 4 ] [ 4 ]                     8 values merged
level 2:  [2] [2] [2] [2]                 8 values merged
level 3:  [1][1][1][1][1][1][1][1]        (single values: nothing to do)

So the total work is n per level × log₂ n levels = O(n log n). Quick sort has the same structure if the pivot splits each range roughly in half.

python · try it yourself
import math

def merge_sort(a, stats, depth=0):
    stats["depth"] = max(stats["depth"], depth)
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid], stats, depth + 1), merge_sort(a[mid:], stats, depth + 1)
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        stats["comps"] += 1
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

for n in [16, 256, 4096]:
    data = [(k * 2654435761) % 1000003 for k in range(n)]      # scrambled values
    stats = {"comps": 0, "depth": 0}
    merge_sort(data, stats)
    print(f"n={n:>5}: levels {stats['depth']:>2} (log2 n = {math.log2(n):.0f}), "
          f"comparisons {stats['comps']:>6}, n·log2 n = {int(n * math.log2(n)):>6}")
n=   16: levels  4 (log2 n = 4), comparisons     49, n·log2 n =     64
n=  256: levels  8 (log2 n = 8), comparisons   1758, n·log2 n =   2048
n= 4096: levels 12 (log2 n = 12), comparisons  44359, n·log2 n =  49152

The recursion depth is exactly log₂ n, and the comparisons stay just below n log₂ n.

Quick sort: average vs worst case

With the last element as pivot, sorted input makes every partition maximally unbalanced: one side empty, the other with n - 1 values. The recursion becomes n levels deep and the comparisons add up to n(n-1)/2 again. Watch how the pivot always ends up at the right end and only one value is fixed per partition:

python · try it yourself
def quick_sort(a, lo, hi, stats, depth=1):
    if lo >= hi:
        return
    stats["depth"] = max(stats["depth"], depth)
    pivot, i = a[hi], lo
    for j in range(lo, hi):
        stats["comps"] += 1
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]
    quick_sort(a, lo, i - 1, stats, depth + 1)
    quick_sort(a, i + 1, hi, stats, depth + 1)

for name, data in [("sorted 6", list(range(1, 7))), ("sorted 500", list(range(500))),
                   ("scrambled 500", [(k * 263) % 500 for k in range(500)])]:
    stats = {"comps": 0, "depth": 0}
    quick_sort(data, 0, len(data) - 1, stats)
    print(f"{name:>13}: {stats['comps']:>6} comparisons, depth {stats['depth']}")
     sorted 6:     15 comparisons, depth 5
   sorted 500: 124750 comparisons, depth 499
scrambled 500:   4847 comparisons, depth 20

Sorted input of 6 values needs 6·5/2 = 15 comparisons, the same as the animation shows ("Is … < pivot?" steps). For 500 sorted values, quick sort does 124,750 comparisons; on scrambled data it needs only a few thousand. Choosing the pivot well (median-of-three or a random index) makes the bad case extremely unlikely.

Counting sort and radix sort: beyond comparisons

It can be proven that any sort that only compares values needs at least log₂(n!) ≈ n log₂ n comparisons in the worst case: there are n! possible orderings, and each comparison can at best halve the number still possible. Counting sort and radix sort avoid comparisons entirely:

Algorithm Time Extra memory Restriction
Counting sort O(n + k) O(k) integer keys in a range of size k
Radix sort (LSD) O(d · (n + b)) O(n + b) d digits in base b
python · try it yourself
import math

def counting_sort_ops(values):
    k = max(values) + 1
    return len(values) + k            # count each value, then walk the counters

def radix_sort_ops(values, base=10):
    digits = len(str(max(values)))
    return digits * (len(values) + base)

for n in [1_000, 100_000]:
    small = [(i * 7) % 100 for i in range(n)]          # values below 100
    large = [(i * 7919) % 10**9 for i in range(n)]     # values up to a billion
    print(f"n={n:>7,}: n·log2 n ≈ {int(n * math.log2(n)):>9,} | "
          f"counting(small) {counting_sort_ops(small):>9,} | "
          f"counting(large) {counting_sort_ops(large):>13,} | "
          f"radix(large) {radix_sort_ops(large):>9,}")
n=  1,000: n·log2 n ≈     9,965 | counting(small)     1,100 | counting(large)     7,912,082 | radix(large)     7,070
n=100,000: n·log2 n ≈ 1,660,964 | counting(small)   100,100 | counting(large)   791,992,082 | radix(large)   900,090

Counting sort is unbeatable for small ranges and useless for huge ones; radix sort handles large keys with a handful of passes.

Summary

Algorithm Best Average Worst Memory Stable
Merge sort O(n log n) O(n log n) O(n log n) O(n) yes
Quick sort O(n log n) O(n log n) O(n²) O(log n) no
Heap sort O(n log n) O(n log n) O(n log n) O(1) no
Counting sort O(n + k) O(n + k) O(n + k) O(k) yes (prefix-sum version)
Radix sort O(d(n + b)) O(d(n + b)) O(d(n + b)) O(n + b) yes

Test yourself

Why does merge sort take O(n log n) time?

  1. It compares every pair
  2. There are about log₂ n levels of splitting and each level does O(n) merging work
  3. It sorts in place
  4. It uses a hash table

What is quick sort's worst-case time complexity?

  1. O(n)
  2. O(n log n)
  3. O(n²)
  4. O(2ⁿ)

How can counting sort beat the n log n lower bound?

  1. It is not a real sort
  2. It doesn't compare values; it uses them as array indexes
  3. It only sorts small arrays
  4. The bound only applies to merge sort