You just watched merge sort cut ten numbers into single pieces, then merge them back, two sorted pieces at a time. One number on its own is already sorted, so all the real work happens in the merge.
Quick check
Quick check: The last merge joins [1, 2, 5, 8, 9] and [3, 4, 6, 7, 10]. Which half runs out first?
Merging two sorted halves#
Keep one index on the front of each half. Compare the two fronts, take the smaller one, and move that index forward. This is the two pointers idea from stage 3. When one half runs out, whatever is left in the other half is already sorted and bigger than everything placed so far, so copy it straight to the end.
- L = [2, 5, 8]
- R = [1, 3, 9]
- out, i, j = [], 0, 0
- while i < len(L) and j < len(R):
- if L[i] <= R[j]:
- out.append(L[i])
- i += 1
- else:
- out.append(R[j])
- j += 1
- out += L[i:] + R[j:]
- print(out)
Variables
L
Left half, already sorted.
Quick check
Quick check: You merge [4, 6] and [1, 2, 3]. How many comparisons does the merge make?
Split until one item#
msort splits the list at the middle, sorts each half by calling itself, and merges the answers. The calls stop at the base case: a list with one item or none is already sorted, so it is returned as it is. heapq.merge is Python's ready-made version of the merge above, used here only to keep the trace short. It gives its answer one item at a time, so list() collects them. In an interview, write your own merge. Drag n down to 1, then to 0.
n- from heapq import merge
- def msort(a):
- if len(a) <= 1:
- return a
- m = len(a) // 2
- L = msort(a[:m])
- R = msort(a[m:])
- return list(merge(L, R))
- n = 4
- nums = [5, 2, 8, 1][:n]
- print(msort(nums))
Variables
None yet
heapq.merge merges the same way as our merge.
Quick check
Quick check: Set n to 1, so the list is [5]. After the first call, how many more calls to msort happen?
At n = 4 the deepest point is three calls stacked up: [5, 2, 8, 1], then [5, 2], then [5]. Halving keeps the stack about log₂ n + 1 calls deep, here 2 + 1 = 3, which is O(log n).
Why it is O(n log n) every time#
Every split halves the pieces, so n items become single items after about log₂ n levels. On the way back up, the pieces at each level together hold all n items, and a merge costs about as much as its size. That is n work per level, for log n levels: O(n log n).
Quick check
Quick check: How many levels of splitting does merge sort need for 1024 items?
Quick check
Quick check: A placement portal sorts 10 lakh roll numbers. About how many steps does merge sort take?
Best, average and worst case#
| Case | Input | Time |
|---|---|---|
| Best | Already sorted | O(n log n) |
| Average | Random order | O(n log n) |
| Worst | Sorted halves that alternate, like [1, 5, 3, 7, 2, 6, 4, 8] | O(n log n) |
Extra space is O(n) for the merged copies, plus O(log n) for the call stack, whatever the input.
The input changes how many comparisons a merge makes, but every merge still copies all of its items. A sorted list is still split and merged level by level, so the best case stays O(n log n), not O(n) like insertion sort. A sort is in place if it needs only a few extra variables, O(1) space, beyond the list itself. Merge sort is not: each merge writes into a new list of up to n items, so it needs O(n) extra space, plus O(log n) for the call stack.
Stable, because ties go left#
A sort is stable if equal values keep the order they started in. Asha (roll 101) and Ravi (roll 103) both scored 72, and the list started in roll number order, so Asha comes first. Watch the tie.
When to use it#
| Situation | Why merge sort fits |
|---|---|
| Sorting a linked list | A linked list can only be read front to back, and the merge only ever reads front to back |
| Data too big for memory | Sort chunks that fit, then merge the sorted files, reading each one front to back (external sorting) |
| You need n log n guaranteed, and stability | No input can slow it down. The built-in sort in Python and Java (for objects) uses merging for the same reason |
For a plain array in memory, quick sort is often faster in practice because it needs no extra copy.
The same code in five languages#
Here is the full merge sort with our own two-index merge in place of heapq.merge, in Python, C++, C, Java and Go. In an interview, write it this way.
One last check#
Quick check
Quick check: Merge sort runs on 8 student records that are already sorted by marks. Which is true?
Next you play the merge sort visualizer yourself, then meet quick sort, which also splits the list but does it by swapping items inside the list, so it needs no extra copy.