Merge Sort and Quicksort: How They Work and What They Cost
Merge sort and quicksort are the two classic divide-and-conquer sorts. Both split the list, sort the pieces recursively and finish in O(n log n) time in the typical case. They put the real work in opposite places: merge sort splits trivially and works hard to combine, quicksort works hard to split and has nothing left to combine. That one difference explains their guarantees, their memory use and their stability. Examples use Python 3.10 or later and only the standard library.
Merge sort
Split the list into two halves, sort each half recursively, then merge the two sorted halves into one sorted list. The merge walks both halves with one index each and repeatedly takes the smaller front item, so it costs O(n) for n items. A list of length 0 or 1 is already sorted, which ends the recursion.
def merge_sort(a, key=lambda x: x):
if len(a) <= 1:
return list(a)
mid = len(a) // 2
left = merge_sort(a[:mid], key) # sort each half
right = merge_sort(a[mid:], key)
return merge(left, right, key)
def merge(left, right, key):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if key(right[j]) < key(left[i]): # take from the right only if strictly smaller
out.append(right[j])
j += 1
else: # ties go to the left half: stable
out.append(left[i])
i += 1
out.extend(left[i:]) # one of these is empty
out.extend(right[j:])
return out
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
cards = [("B", 1), ("A", 2), ("B", 3), ("A", 4)]
print(merge_sort(cards, key=lambda c: c[0]))
[3, 9, 10, 27, 38, 43, 82]
[('A', 2), ('A', 4), ('B', 1), ('B', 3)]
The comparison in merge takes from the right half only when its item is strictly smaller, so on a tie the item from the left half, which came first in the input, goes first. That makes merge sort stable: the two A cards and the two B cards keep their input order. Writing <= there would quietly break stability.
What merge sort costs
The recursion is T(n) = 2T(n/2) + O(n): two half-size problems plus a linear merge. There are about log2 n levels of halving, and the merges on each level together touch all n items, so the total is O(n log n) in the best, average and worst case. The input order does not matter; merge sort does the same splitting on every input. In master theorem terms, a = 2, b = 2, d = 1, and the Master Theorem Calculator returns Case 2, "Θ(n log n)".
The cost is memory. Merging two halves of an array needs a buffer to write into, so merge sort on arrays uses O(n) extra space (this version also creates new lists when slicing, but even a careful version needs the O(n) buffer). Its recursion depth is only O(log n). On linked lists, merging can relink nodes instead, and no buffer is needed. John von Neumann is credited with describing merge sort in 1945.
Quicksort
Pick an item as the pivot. Partition the list so that everything smaller than the pivot comes before it and everything else after it; the pivot is then in its final position. Sort the two sides recursively. No combining step is needed, because the sides are already in the right order relative to each other. Tony Hoare developed quicksort and published it in 1961 as "Algorithm 64" in the Communications of the ACM.
The partition below is the Lomuto scheme: the pivot is the last item, and one index i marks the end of the "smaller than the pivot" region while j scans the rest. (Hoare's original scheme moves two indices toward each other and usually makes fewer swaps, but it is harder to get right.) The program counts comparisons and the deepest level of recursion, with two pivot rules, on random and on sorted input:
import random
def partition(a, lo, hi, stats):
"""Lomuto scheme: pivot a[hi]; returns the pivot's final index."""
pivot = a[hi]
i = lo # a[lo:i] holds items < pivot
for j in range(lo, hi):
stats["comparisons"] += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i] # put the pivot between the parts
return i
def quicksort(a, lo, hi, stats, randomize, depth=1):
if lo >= hi:
return
stats["depth"] = max(stats["depth"], depth)
if randomize: # random pivot: swap it to the end
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
p = partition(a, lo, hi, stats)
quicksort(a, lo, p - 1, stats, randomize, depth + 1)
quicksort(a, p + 1, hi, stats, randomize, depth + 1)
random.seed(11)
n = 500
for name, data in [("random input", random.sample(range(n), n)),
("sorted input", list(range(n)))]:
for randomize in (False, True):
a = list(data)
stats = {"comparisons": 0, "depth": 0}
quicksort(a, 0, n - 1, stats, randomize)
assert a == sorted(data)
pivot = "random pivot" if randomize else "last-item pivot"
print(f"{name}, {pivot:15}: {stats['comparisons']:6} comparisons, "
f"depth {stats['depth']}")
print("n*(n-1)/2 =", n * (n - 1) // 2)
random input, last-item pivot: 4626 comparisons, depth 19
random input, random pivot : 4637 comparisons, depth 20
sorted input, last-item pivot: 124750 comparisons, depth 499
sorted input, random pivot : 4700 comparisons, depth 17
n*(n-1)/2 = 124750
Average case, worst case and pivot choice
When pivots split the list roughly in half, quicksort has the same shape as merge sort: about log2 n levels of O(n) partitioning, O(n log n). On random input that is what happens on average: about 4,600 comparisons for 500 items, with a recursion depth near 20.
When the pivot is always the smallest or largest item, each partition peels off just one item, the levels number n, and the total is n(n - 1)/2 comparisons: O(n^2), the worst case. The last-item pivot does exactly that on input that is already sorted: 124,750 comparisons for 500 items, with recursion 499 levels deep. Sorted and nearly sorted input are common in real data, which makes a fixed first-item or last-item pivot a poor choice.
A random pivot fixes the dependence on input order. No particular input is bad any more; for every input, the expected running time is O(n log n), and the sorted list took 4,700 comparisons in this run. The O(n^2) worst case still exists, but only through a long run of unlucky random choices, which is extremely unlikely for large n. Median-of-three (the median of the first, middle and last items) is a common deterministic alternative that handles sorted input well, though specially built inputs can still defeat it.
Recursion depth and space
Quicksort sorts in place, but its recursion uses stack space. With balanced splits the depth is O(log n); in the worst case it is O(n), and the 499-level run above would exceed Python's default recursion limit of 1000 for a list a few times larger. The fix is to recurse into the smaller part and loop on the larger one. The smaller part is at most half the current range, so each nested call halves the size, and the depth is O(log n) even when the time is O(n^2):
def partition(a, lo, hi):
pivot, i = a[hi], lo # Lomuto, last-item pivot
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, depth=1, stats=None):
"""Recurse into the smaller part, loop on the larger: depth O(log n)."""
if hi is None:
hi = len(a) - 1
stats["depth"] = max(stats["depth"], depth)
while lo < hi:
p = partition(a, lo, hi)
if p - lo < hi - p:
quicksort(a, lo, p - 1, depth + 1, stats)
lo = p + 1 # continue with the larger right part
else:
quicksort(a, p + 1, hi, depth + 1, stats)
hi = p - 1 # continue with the larger left part
a = list(range(5000)) # the worst case for this pivot rule
stats = {"depth": 0}
quicksort(a, stats=stats)
print(a == sorted(a), "max recursion depth:", stats["depth"])
True max recursion depth: 2
On 5,000 sorted items, the worst case for this pivot rule, the depth stays at 2, because each smaller part is empty. The running time is still quadratic; only the stack is protected.
Stability
The usual in-place quicksort is not stable. Partitioning swaps items across long distances, so equal keys can change order:
def partition(a, lo, hi, key):
pivot, i = key(a[hi]), lo
for j in range(lo, hi):
if key(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, hi, key):
if lo < hi:
p = partition(a, lo, hi, key)
quicksort(a, lo, p - 1, key)
quicksort(a, p + 1, hi, key)
cards = [("B", 1), ("A", 2), ("B", 3), ("A", 4)]
quicksort(cards, 0, len(cards) - 1, key=lambda c: c[0])
print(cards)
[('A', 4), ('A', 2), ('B', 1), ('B', 3)]
The ("A", 4) card now comes before ("A", 2). Stable versions exist, but they partition into separate lists and give up the in-place advantage.
Side by side
| Merge sort | Quicksort | |
|---|---|---|
| Where the work happens | Combining (merge) | Dividing (partition) |
| Best and average time | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n^2) |
| Extra space (arrays) | O(n) buffer, O(log n) stack | O(log n) stack on average, O(n) worst; O(log n) with smaller-part-first |
| Stable | Yes | No (in-place form) |
| Sensitive to input order | No | Yes with a fixed pivot; expected O(n log n) with a random pivot |
The Algorithm Comparison Tool shows the same picture: at n = 1000, both sorts get 9,965.78 (n log2 n) in the average case, and in the worst case quicksort jumps to 1,000,000 (n^2) while merge sort stays put. The tool lists quicksort's space as O(log n), the typical recursion depth.
Which is faster in practice?
For sorting arrays in memory, a well-implemented quicksort is usually faster than merge sort, even though both are O(n log n). Its inner loop is simple, it works in place without copying into a buffer, and it scans memory sequentially, which suits the processor cache. That is a statement about constant factors in typical implementations, not a law: in Python, both hand-written versions are far slower than the built-in sorted(), so measure with timeit on your own data if speed matters. Merge sort wins when you need stability, a worst-case guarantee, sorting of linked lists, or sorting data too large to fit in memory, where merging sorted runs from disk is the natural method.
Both are instances of the general pattern in divide and conquer.
Check yourself
- Why is merge sort O(n log n) even on sorted input, while bubble sort with an early exit is O(n) there? (Merge sort always splits down to single items and merges every level; it never checks whether the input is already sorted.)
- Which input makes a first-item-pivot quicksort take O(n^2) time? (Sorted or reverse-sorted input.)
- With a random pivot, is quicksort's worst case still O(n^2)? (Yes, but the expected time is O(n log n) for every input.)