Sub topic 2
Why Merge Sort Is Correct
This chapter assumes you know the merge and merge_sort functions from the previous chapter, recursion, and Big-O notation. It covers four properties of merge sort: why it is correct, how fast it runs, how much extra memory it uses, and why it is stable.
Correctness by Induction
The proof uses strong induction on the input length n.
- Base case: a list with 0 or 1 elements is already sorted, and
merge_sortreturns a copy of it unchanged. - Inductive step: assume
merge_sortcorrectly sorts every list shorter than n. Both halves have fewer than n elements, so each recursive call returns a sorted list.mergealways appends the smaller of the two front elements. So, given two sorted inputs, it produces one sorted output that contains every element exactly once.
A common mistake is to treat merge as correct without checking it. The two extend calls matter. Leave them out and you lose the elements that remain after one side runs out.
Deriving O(n log n) from the Recurrence
Splitting a list costs O(n) when you use slicing. Merging also costs O(n). Together they give the recurrence T(n) = 2T(n/2) + cn.
Level k of the tree holds 2^k subproblems, each of size n/2^k. That makes the work at every level cn. The input halves at each level, so there are log₂ n + 1 levels. The total is cn(log₂ n + 1) = O(n log n). This bound holds for every input, including inputs that are already sorted, because the splits never depend on the data.
Auxiliary Space
Each merge builds a new list as long as its inputs. Only one merge is active at any moment along a path of the recursion, so peak extra memory is O(n) for the merge buffers. The call stack adds O(log n). The slicing in items[:mid] also makes copies, but those copies sum to O(n) along any single root-to-leaf path. The usual array version therefore needs O(n) extra space. Heapsort, by comparison, needs only O(1).
Stability and Why the Merge Uses `<=`
A sort is stable if equal keys stay in their original relative order. When left[i] == right[j], the test left[i] <= right[j] takes from the left half first. The left half holds the elements that came earlier in the input, so ties keep their original order.
def merge(left, right, key):
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
if key(left[i]) <= key(right[j]):
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
return result + left[i:] + right[j:]
print(merge([("a", 1)], [("b", 1)], key=lambda p: p[1]))
# [('a', 1), ('b', 1)]Exercise
Why does merge sort take O(n log n) time on an already-sorted list, while insertion sort takes O(n) on the same list?
Show answer
Merge sort always splits in the middle and runs every merge, so each of its log n levels does linear work no matter what order the input is in. Insertion sort does only one comparison per element when the input is already sorted.
Exercise
The recurrence T(n) = 2T(n/2) + cn gives n log n. What would T(n) = 2T(n/2) + c (constant merge cost) give?
Show answer
O(n). The work per level is c, 2c, 4c, and so on, up to about cn at the leaves. This geometric series sums to O(n).