In which order does merge-sort work through 7 2 9 4 3 8 6 1?
Depth-first, left before right: it cuts its way down the left side to single elements, merges 7 | 2 into 2 7 and 9 | 4 into 4 9, merges those into 2 4 7 9, and only then starts on the right half 3 8 6 1. The very last step merges 2 4 7 9 with 1 3 6 8.
* The numbers ① to ⑮ give the order in which the calls start. *
A recursive call has to return before the code after it runs, so mergeSort(S2) cannot start until mergeSort(S1) has delivered a completely sorted left half. The run through the tree is a depth-first traversal:
- Calls ① ② ③ cut 7 2 9 4 3 8 6 1 → 7 2 9 4 → 7 2, and calls ④ ⑤ reach the leaves 7 and 2.
- Call ③ merges them into 2 7: the first comparison of the whole run.
- Call ⑥ turns 9 4 into 4 9 the same way, then call ② merges 2 7 and 4 9 into 2 4 7 9.
- The right half repeats the pattern with calls ⑨ to ⑮: 3 8 and 1 6, merged into 1 3 6 8.
- Call ① merges 2 4 7 9 with 1 3 6 8 into 1 2 3 4 6 7 8 9.
A merge runs as soon as both children of its node have returned, so the merges happen in postorder: children first, then the parent. The call stack never holds more than one call per level, here at most four (from the root down to a leaf).
Go deeper:
Merge-sort with Transylvanian-saxon folk dance — the same split-then-merge order, danced by ten people holding numbers.