Mental model
Merging is the easy part. Given two piles of cards, each already sorted, you can produce one sorted pile by repeatedly looking at the two top cards and taking the smaller. You never look further than the tops, and every card is moved exactly once.
Merge sort makes everything else into that easy part:
- Split the range in half at
mid. - Sort each half, by the same method (recursion).
- Merge the two sorted halves.
A range of zero or one elements is already sorted: that is the base case that stops the recursion.
The lab shows three regions at once: the array, the auxiliary buffer, and the call stack,
one slab per sortRange call that has started but not yet returned. The coloured brackets behind
the array are the ranges of those calls, innermost brightest.
The recursion
sortRange(low, high) sorts the half-open range [low, high). For eight elements the calls happen
in this order: sort [0, 8) → sort [0, 4) → sort [0, 2) → sort [0, 1) (base case) → sort
[1, 2) (base case) → merge [0, 2) → sort [2, 4) → … The left half is always finished before
the right half starts, so the stack never holds more than one path from the whole range down to a
single element: at most ⌈log₂ n⌉ + 1 frames. Watch the Max stack depth metric: 4 for eight
elements.
Merging through a buffer
You cannot merge two halves in place by simply writing into the array: the first write would overwrite an element that has not been placed yet. This implementation therefore:
- Copies
[low, high)into the same positions of the buffer (the array slots fade in the lab: their contents are safe in the buffer and may be overwritten). - Walks the two halves of the buffer with
i(left) andj(right), writing the smaller front element toitems[k]. - When one half runs out, copies the rest of the other half without comparing.
The buffer is allocated once, with n slots, and every merge borrows the part under its own range. Allocating a new temporary array in every call would give the same O(n) peak memory but far more allocations.
Stability
A sort is stable if elements that compare equal keep their original relative order. That matters as soon as you sort records by one field: sort orders by date, then stably by customer, and each customer's orders stay in date order.
Merge sort is stable because of one character. On a tie, the merge takes the left element
(compare(left, right) <= 0, or in C++ !less(right, left)). Every left element started before
every right element, so equal values never overtake each other. Write < instead and the sort
still sorts, but it is no longer stable. In the lab, repeated values carry letters (5a, 5b, 5c);
run the Equal values stay in order preset and the letters come out in order.
Why it is O(n log n)
Let T(n) be the cost of sorting n elements. Two recursive calls on halves plus a linear merge:
T(n) = 2·T(n/2) + c·n, T(1) = c
Draw it as a tree. Level 0 is one merge of n elements; level 1 is two merges of n/2; level 2 is four of n/4. Every level does about c·n work in total, and halving reaches 1 after ⌈log₂ n⌉ levels. So T(n) = Θ(n log n). The same recurrence appears again in M29 with the Master theorem.
Concretely, for this implementation:
| Measure | Bound | Note |
|---|---|---|
| Comparisons | ≤ n·⌈log₂ n⌉ | a merge of m elements compares at most m − 1 times |
| Element writes | 2n per level, 2n·⌈log₂ n⌉ for powers of two | copy out, merge back |
sortRange calls |
2n − 1 | n base cases plus n − 1 splits |
| Extra space | n buffer slots + O(log n) stack frames | O(n) |
Unlike quicksort, nothing depends on the input order: sorted, reversed and random inputs all cost Θ(n log n). Sorted input saves comparisons (each merge drains one half early, as the Already sorted preset shows), but this simple version still copies everything at every level. Production merge sorts such as Timsort detect already sorted runs and do much less work on them.
Built-in sorts and stability
| Language | Stable | Not stable |
|---|---|---|
| C# | Enumerable.OrderBy / ThenBy (LINQ, returns a new sequence) |
Array.Sort, List<T>.Sort, Span<T>.Sort: introspective sort, documented as unstable |
| Python | list.sort() and sorted(): guaranteed stable (Timsort, a merge sort over natural runs) |
— |
| Java | Arrays.sort(Object[]), List.sort, Collections.sort: guaranteed stable (a TimSort adaptation) |
Arrays.sort(int[]) and other primitives: dual-pivot quicksort; stability is meaningless for primitives anyway |
| C++ | std::stable_sort: O(n log n) comparisons with enough extra memory, O(n log² n) without |
std::sort: O(n log n) comparisons, no stability guarantee |
The algorithms named here are implementation details of the current runtimes; the stability guarantee (or its absence) is the documented contract you can rely on.
The teaching implementation
Sort / merge_sort takes a comparison so the tests can sort records by a key and check stability.
The four versions differ only where the languages force it: Java cannot create a generic array, so
it allocates an Object[] and casts once; C++ fills the buffer with default-constructed values; and
Python's version takes a key function like list.sort. All four read one shared fixture file
whose tokens such as 3a 3b must come out in their original order, and each is compared with its
language's stable built-in sort on 500 random inputs.
Common mistakes
<instead of<=in the merge comparison: the output is sorted but no longer stable.- Forgetting to drain the remaining half: the elements left in the buffer are lost.
- Allocating a new buffer in every merge: correct but slow; allocate once and pass it down.
- Assuming the built-in sort is stable. In C#
Array.SortandList<T>.Sortare not; useOrderByor include a tie-breaking key. - Splitting on
(low + high) / 2in fixed-width integers: the same overflow as in binary search.
Edge cases
- Empty array and one element: the first call is already a base case; nothing is compared or written.
- All elements equal: every comparison is a tie and takes the left element; the order is unchanged.
- Odd lengths:
midrounds down, so the left half is the smaller one and the recursion tree is slightly unbalanced (the Odd length preset).
Worked practice
1. How many element comparisons can merging a sorted half of 3 with a sorted half of 5 need at most?
Answer
7 (= 3 + 5 − 1). Each comparison places one element; once one half is empty, the last elements are copied without comparing, and at least one element is always copied that way.
2. Why is the call stack depth O(log n) even though there are 2n − 1 calls?
Answer
Calls run one after another, not all at once. A frame is on the stack only while one of its descendants is running, so the stack holds one root-to-leaf path of the recursion tree, which has ⌈log₂ n⌉ + 1 levels.
3. You sort people by name with a stable sort, then by age with a stable sort. In what order are people of the same age?
Answer
By name. The second, stable sort keeps the name order among people whose ages are equal. Sorting by the least significant key first and the most significant key last is how multi-key sorting with stable sorts works.
Summary
- Merge sort splits until ranges are trivial, then merges sorted halves in linear time.
- Θ(n log n) time in every case; O(n) extra space for the buffer plus O(log n) stack.
- Taking the left element on ties (
<=) makes it stable. - Python's and Java's object sorts are stable; C#'s
Array.Sortand C++'sstd::sortare not.