Objective
Implement merge sort, quicksort partitioning and heapsort, derive quicksort's expected number of comparisons, explain stability with a concrete failure, find a -th smallest value in expected linear time, and outline how to sort data far larger than memory. (The comparison lower bound, counting sort and binary search are covered in the Foundations module; this lesson goes inside the algorithms.)
Merge sort, and counting inversions on the way
Merge sort splits the array in half, sorts each half, and merges the two sorted halves with two pointers. The recursion has levels, each doing merging: in every case, extra space, and stable if ties are taken from the left half.
The merge also counts inversions, pairs with , for free: when an element of the right half is placed before the remaining left-half elements, it is inverted with all of them.
def merge_count(a):
"""Return (sorted copy of a, number of inversions i < j with a[i] > a[j])."""
if len(a) <= 1:
return a[:], 0
mid = len(a) // 2
left, x = merge_count(a[:mid])
right, y = merge_count(a[mid:])
out, i, j, inv = [], 0, 0, x + y
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= takes ties from the left: stable
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
inv += len(left) - i # right[j] jumps every remaining left item
out += left[i:] + right[j:]
return out, inv
print(merge_count([3, 1, 4, 1, 5, 9, 2, 6])) # ([1, 1, 2, 3, 4, 5, 6, 9], 8)
Inversions measure how far two rankings disagree, which is how Kendall's is computed in instead of : order the items by one ranking, count inversions in the other, and (no ties). A signal that ranks five stocks while realised returns rank them has and .
Quicksort and partitioning
Quicksort picks a pivot, partitions the array into "less than pivot" and "at least pivot", puts the pivot between them, and recurses on both sides. All the work is in the partition. Lomuto's scheme keeps a[lo:i] below the pivot as j scans:
import random
def partition(a, lo, hi):
"""Pivot a[hi]; returns its final index p with a[lo:p] < pivot <= a[p+1:hi+1]."""
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
while lo < hi:
r = random.randint(lo, hi) # random pivot: no bad inputs, only bad luck
a[r], a[hi] = a[hi], a[r]
p = partition(a, lo, hi)
if p - lo < hi - p: # recurse on the smaller side, loop on the larger
quicksort(a, lo, p - 1)
lo = p + 1
else:
quicksort(a, p + 1, hi)
hi = p - 1
t = [7, 2, 9, 4, 3, 8, 5]
print(partition(t, 0, len(t) - 1), t) # 3 [2, 4, 3, 5, 9, 8, 7]
Recursing only on the smaller side bounds the stack at even when the split is bad. Hoare's original scheme (two pointers moving inwards) does about three times fewer swaps and is what libraries build on.
Many duplicates. If every key is equal, Lomuto puts everything on one side and quicksort becomes . A three-way partition (Dutch national flag) splits into , and in one pass and never recurses into the equal block; on [3, 5, 3, 1, 3, 7, 2, 3] with pivot 3 it produces [1, 2, 3, 3, 3, 3, 7, 5] with the equal block at indices 2 to 5. Prices on a tick grid have heavy duplication, so this matters.
Worked example
quicksort's expected comparisons
With uniformly random pivots and distinct keys, what is the expected number of comparisons quicksort makes on items? Evaluate it for and for large .
Show solutionHide solution
Label the keys by rank, . Two keys are compared only if one of them is a pivot while both are still in the same subarray. Consider the block . Until some key in the block is chosen as a pivot, the block stays together. The first pivot chosen from the block is equally likely to be any of its keys. If it is or , they are compared; if it is anything in between, they are separated forever. So
Summing over pairs by linearity of expectation,
where . For , and ; the recurrence gives the same exact fraction. For large , , so : about 39% above the information-theoretic minimum of . For the exact formula gives about .
The worst case, comparisons, needs the pivot to be an extreme of its subarray at nearly every step, which is exponentially unlikely with random pivots. Introsort (used by C++'s std::sort) switches to heapsort if the recursion gets too deep, making the worst case .
Heapsort
Build a max-heap in the array, then repeatedly swap the maximum to the end, shrink the heap by one and sift the new root down.
def heapsort(a):
n = len(a)
def sift_down(i, size):
while True:
big, l, r = i, 2 * i + 1, 2 * i + 2
if l < size and a[l] > a[big]:
big = l
if r < size and a[r] > a[big]:
big = r
if big == i:
return
a[i], a[big] = a[big], a[i]
i = big
for i in range(n // 2 - 1, -1, -1): # build the heap bottom-up
sift_down(i, n)
for end in range(n - 1, 0, -1): # move the max to the end, then repair
a[0], a[end] = a[end], a[0]
sift_down(0, end)
t = [5, 2, 9, 1, 7, 3]
heapsort(t)
print(t) # [1, 2, 3, 5, 7, 9]
Building the heap is , not . About nodes sit at height , and sifting one down costs , so the total is because . The extraction phase is sifts of , so heapsort is worst case with extra space. It loses to quicksort in practice because its jumps between and are cache-unfriendly, and it is not stable.
Stability, concretely
Sort the records [(2, "a"), (1, "b"), (2, "c"), (1, "d")] by their number. A stable sort (sorted, merge sort) returns [(1, "b"), (1, "d"), (2, "a"), (2, "c")]. The heapsort above, keyed on the number, returns [(1, "b"), (1, "d"), (2, "c"), (2, "a")]: the two 2s swapped. If those records were orders and the first sort was by arrival time, an unstable second sort by price would break time priority. When you need stability from an unstable algorithm, add the original index as a tie-breaker key.
Quickselect: the k-th smallest in expected O(n)
To find one order statistic, partition as in quicksort but recurse only into the side that contains position . The expected work is , roughly linear (about comparisons for the median), with the same worst case as quicksort. The median-of-medians pivot rule makes it worst case, but with a large constant; mention it, do not code it unless asked.
import random
def quickselect(a, k):
"""k-th smallest value (k = 0 is the minimum), expected O(n). Uses O(n) extra space."""
while True:
pivot = random.choice(a)
lows = [x for x in a if x < pivot]
highs = [x for x in a if x > pivot]
n_eq = len(a) - len(lows) - len(highs)
if k < len(lows):
a = lows
elif k < len(lows) + n_eq:
return pivot
else:
k -= len(lows) + n_eq
a = highs
print(quickselect([4, 1, 7, 3, 3, 9, 2], 3)) # 3
The three-way split handles duplicates: sorted, the list is [1, 2, 3, 3, 4, 7, 9], and index 3 is the second 3. An in-place version uses the partition function above.
Where it shows up. Historical-simulation VaR at 99% from 1,000 PnL scenarios is about the 10th-worst outcome: quickselect(pnl, 9) finds it in expected without sorting all scenarios. Alternatives: heapq.nsmallest(10, pnl) in , which also returns the whole tail, or numpy.partition. For a running quantile over a stream, a single selection is not enough; that is the two-heap or sorted-container problem.
External sorting
To sort 100 GB with 4 GB of memory:
- Run generation. Read 4 GB at a time, sort it in memory, write it out as a sorted run: 25 runs.
- -way merge. Open all 25 runs with a buffer each, and repeatedly emit the smallest head using a min-heap of size 25 (
heapq.mergedoes exactly this lazily). Each output element costs .
With 25 buffers of about 150 MB each, one merge pass suffices, so every byte is read twice and written twice. The cost is dominated by I/O, not comparisons, so the design goal is to minimise passes: larger runs (replacement selection produces runs about twice the memory size on random input) and a wider merge both help. The same structure powers sort-merge joins and merging per-exchange tick files into one time-ordered stream.
Knowledge check
How many inversions does [5, 3, 4, 1, 2] contain?
Knowledge check
With random pivots, what is the probability that quicksort ever compares the smallest and the largest of distinct keys?
Knowledge check
You need the median of 10 million PnL values once, and memory is fine. Which approach has the best expected time?
Knowledge check
Why does building a binary heap from n unsorted items take O(n) rather than O(n log n)?
Key takeaways
- Merge sort is always, stable, extra space, and counts inversions (hence Kendall's ) during the merge.
- Quicksort's cost is in partitioning; random pivots give expected comparisons, three-way partitioning handles duplicates, and recursing on the smaller side bounds the stack.
- Heapsort is worst case in space; heap construction is ; it is unstable and cache-unfriendly.
- Stability preserves earlier orderings (time priority); add the original index as a tie-breaker when an algorithm lacks it.
- Quickselect finds a -th smallest in expected ; external sort is sorted runs plus a heap-based -way merge, optimised for I/O passes.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).