Data Structures · Sorting

Merge Sort — top-down recursion: call tree, merges, complexity

🌳 Call tree, array, L·R buffers and the call stack

current call / merge in progresssorted / written backnot reached yetnode = range [l..r]
current array

🧾 One row per merge (bottom-up order of the recursion)

💬 Current step

💻 The courseware C++

Yellow = the line being executed. Recurse all the way down to a leaf (l==r), then merge two sorted runs on the way back out — the merge order is exactly the table, top to bottom.

📄 Answers to both exercises & complexity

1Split: m=(l+r)/2, left half then right half, stop at l==r
2Copy both runs into L / R, compare with pointers i / j, write the smaller one back at k
3When one run is exhausted, copy the rest of the other run (no more comparisons)
4Return one level up and merge again — n−1 merges in total, 2n−1 nodes in the call tree
Exercise 1 answer (courseware array [38,27,43,3,9,82,10]):
split: [38,27,43,3,9,82,10] → [38,27,43,3] + [9,82,10] → [38,27] [43,3] [9,82] [10]
merge: [27,38] · [3,43] · [9,82] · [10] → [3,27,38,43] · [9,10,82] → [3,9,10,27,38,43,82]
(6 merges, 14 comparisons — press E in mode 1 to jump to the end; the six table rows are exactly those merges)

Exercise 2 answer [15,12,6,9,3,21,30]:
(a) sorted = [3,6,9,12,15,21,30] (12 comparisons, 6 merges)
(b) time O(n log n): the recursion tree is log₂n deep and each level scans n elements in total; space O(n) — the merge needs the L/R buffers.

Why does already-sorted data cost MORE comparisons? Comparisons happen while both runs still have elements: when reversed, one run is usually drained early and the rest is copied without comparing (this page: 11 for sorted, 9 for reversed); when sorted, the two runs interleave almost every step. So the comparison count depends on the input order, while the running time stays O(n log n).

Stability: the key is if(L[i] <= R[j]) — on a tie the left run wins, so equal keys never swap order → merge sort is stable.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result