Data Structures · Sorting

Merge Sort

🔢 The array a[] and the auxiliary L / R

left run L (pointer i)right run R (pointer j)already merged runsk = write position
result

🧾 Round record (per width)

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The recipe: one pointer per sorted run (i / j), compare, write the smaller one to k and advance; when one run empties, append the rest of the other.

📄 Key points

1Split: width w starts at 1 (every element is its own run)
2Merge: two pointers i / j walk neighbouring runs, taking the smaller value
3Ties take the left run → this keeps it stable
4Double the width until it covers the array: always O(n log n), O(n) extra space
Why always O(n log n)? Every level moves all n elements (O(n)) and the width doubles, giving log₂n levels; each merge is linear, so the total is O(n log n) regardless of the initial order (sorted and reversed input cost the same — that is what makes it more predictable than quicksort).
The price: merging needs an auxiliary array to hold both runs, so O(n) extra space; quicksort and heap sort work in place with O(1)/O(log n).
Why stable? The test is L[i] <= R[j]: on ties the left run wins, and those elements were already in front → relative order preserved.
External sorting: merge sort is the one you can use when the data does not fit in memory — each pass only reads two runs sequentially, with no random access (disk friendly).
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result