Sub topic 1
Why Comparison Sorts Can't Beat n log n
Prerequisites
This chapter assumes you can read Python lists, loops, and functions. You should know Big-O notation and at least one comparison sort, such as merge sort or quicksort.
The Comparison Lower Bound
A comparison sort learns about its input only by asking "is a[i] < a[j]?" You can model any such algorithm as a decision tree. Each internal node is one comparison, and each leaf is one possible output order. The input could arrive in any of n! orders, so the tree needs at least n! leaves. A binary tree with n! leaves has height at least log₂(n!), and log₂(n!) is Θ(n log n). In the worst case, then, every comparison sort makes Ω(n log n) comparisons.
Sorting Without Comparisons
The bound only covers algorithms that compare elements. Suppose the keys are integers in a known range 0..k. You can then use each key directly as an array index. Indexing the array tells you where a key belongs without comparing it to any other key, so the decision-tree argument does not apply.
Counting Sort with a Histogram
The simplest version counts how often each value appears. It then writes the values back out in order:
def counting_sort_simple(a, k):
"""Sort non-negative integers in the range 0..k."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
out = []
for value, c in enumerate(counts):
out.extend([value] * c)
return out
print(counting_sort_simple([3, 1, 4, 1, 5, 2, 0], 5)) # [0, 1, 1, 2, 3, 4, 5]This works for bare integers. It fails for records such as ("ana", 2), because it rebuilds the values from the counts and throws away any data attached to them.
Stability
A sort is stable if records with equal keys keep their original relative order. If ("ana", 2) comes before ("cy", 2) in the input, a stable sort keeps that order in the output. Radix sort, covered later, depends on this property.
Prefix Sums as Positions
To move whole records, you convert counts into starting positions. The exclusive prefix sum at v is the number of keys smaller than v. That number is the first output index for key v:
counts = [1, 2, 1, 1, 1, 1] # tallies for keys 0..5 from the example above
starts = []
total = 0
for c in counts:
starts.append(total)
total += c
print(starts) # [0, 1, 3, 4, 5, 6]Both 1s go into slots 1 and 2. If you place records in input order and increment the start index after each placement, equal keys keep their order, so the sort is stable.
Exercise
The counts for keys 0..3 are [2, 0, 3, 1]. What are the starting output positions for each key?
Show answer
[0, 2, 2, 5]. Key 1 has no items, so its start is the same as key 2's start.