Merge sort — divide and conquer, O(n log n), stable, proof of correctness
WHAT is merge sort?
The genius is that the divide step does no comparisons at all — it's just mid = (lo+hi)/2. All the intelligence lives in merge, which walks two sorted lists with two pointers.
WHY does merging work? (The core sub-routine)
HOW merge works (pointers i, j):
A = [1, 4, 7] i→
B = [2, 3, 9] j→
out = []
cmp 1,2 → take 1 out=[1]
cmp 4,2 → take 2 out=[1,2]
cmp 4,3 → take 3 out=[1,2,3]
cmp 4,9 → take 4 out=[1,2,3,4]
cmp 7,9 → take 7 out=[1,2,3,4,7]
A empty → copy 9 out=[1,2,3,4,7,9]
The diagram

HOW to write it (Python, derived from the definition)
def merge(A, B):
i = j = 0
out = []
while i < len(A) and j < len(B):
# <= (not <) is what makes merge sort STABLE
if A[i] <= B[j]:
out.append(A[i]); i += 1
else:
out.append(B[j]); j += 1
out.extend(A[i:]) # copy leftover
out.extend(B[j:])
return out
def merge_sort(a):
if len(a) <= 1: # base case: already sorted
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)Derive the running time from scratch
Why this recurrence? Two subproblems of half the size (the 2T(n/2)) plus a linear-time merge (cn).
Solve by the recursion tree (HOW):
- Level : 1 problem of size → work .
- Level : 2 problems of size → work .
- Level : problems of size → work .
Every level does work. How many levels? We halve until size : Total levels . Therefore
Proof of correctness (induction on )
Proof by strong induction on .
-
Base case : a list of or element is trivially sorted and is its own permutation. ✓
-
Inductive hypothesis (IH): assume
merge_sortis correct for all lengths . -
Inductive step: for length , we split into
left(size ) andright(size ). By IH both recursive calls return sorted permutations of their halves.Now prove
mergeis correct (loop invariant):- Initialization:
out=[]— vacuously true. - Maintenance: we append , which is everything in
out(by invariant) and all remaining (since sorted). Sortedness and the bound are preserved. - Termination: one list empties; we copy the rest (already sorted and all of
out). Sooutis a sorted permutation of . ✓
Hence
merge(left,right)returns a sorted permutation of . By induction the algorithm is correct for all . - Initialization:
Worked examples
Flashcards
What are the three steps of merge sort?
Why is merge ?
Write the merge sort recurrence.
Why does the recurrence give ?
What is merge sort's best / average / worst time?
What is merge sort's space complexity?
Which comparison keeps merge sort stable, < or <=?
<= (prefer the left element on ties).What is the merge loop invariant?
out is sorted and all remaining elements of both inputs.How do you prove merge sort correct?
Why is merge sort NOT like insertion sort?
Recall Feynman: explain to a 12-year-old
Imagine two friends each holding a sorted stack of numbered cards. To combine them into one sorted stack, you just keep comparing the top card of each stack and taking the smaller — super easy! Merge sort first keeps cutting one messy stack in half until each tiny stack has just one card (already "sorted"), then plays this easy combine-game over and over until the whole thing is sorted. Cutting is free; combining is the smart part.
Connections
- Divide and Conquer — the general paradigm merge sort exemplifies.
- Quick sort — also average but in-place and not stable; merge sort is the stable counterpart.
- Master Theorem — solves directly (Case 2 ⟹ ).
- Big-O Notation — language for the complexity bounds here.
- Stability of Sorting Algorithms — why preserving equal-key order matters.
- Recursion and Induction — the proof technique used above.
- External Sorting — merge sort underlies sorting data too big for RAM.
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, merge sort ka pura funda ek line mein hai: ek badi list ko sort karna mushkil hai, par do already-sorted list ko jodna (merge karna) bahut easy hai. Isliye hum list ko baar-baar aadha-aadha kaatte rehte hain jab tak har piece sirf 1 element ka na ho jaaye — aur size-1 list to khud-ba-khud sorted hoti hai. Phir un sorted tukdo ko wapas merge karke upar le aate hain.
Merge kaise hota hai? Do pointers lagao, dono sorted lists ke front pe. Sabse chhota element hamesha kisi ek list ke aage hi hoga (kyunki peeche wale to bade hain). Compare karo, chhota wala utha lo, us pointer ko aage badha do. Har element bas ek baar touch hota hai, isliye merge O(n) hai. Yahi "lefty wins ties" wala rule — jab dono equal ho to left wala pehle lo — merge sort ko stable banata hai.
Time complexity samjho recursion tree se: har level pe pura ka kaam hota hai (merge), aur list ko aadha karte-karte total levels banti hain. Toh . Aur sabse mast baat — input chahe sorted ho ya ulta, structure same rehta hai, isliye best, worst, average sab . Bas extra memory chahiye, in-place nahi hai.
Correctness ka proof induction se hota hai: size base case sorted hai; phir maan lo chote sizes ke liye sahi hai, toh dono aadhe sorted aate hain, aur merge unhe sahi se jod deta hai (loop invariant se). Bas, exam mein yeh proof + recurrence likh do, full marks pakke.