Proofs: Merge sort
These are the human proofs of Merge sort, at full length.
Merge sort sorts the array and keeps its items full
This proof shows: correctness.
We write for the multiset of the items of at the start of a call.
Lemma (MERGE). Assume that , and that and are sorted. Then after MERGE, is sorted and holds . No other item of changes.
Proof. Let . Line L6 makes , so . Line L7 sets , and . We use this invariant for the loops of lines L8 and L12:
(M) . The part holds and the old , in sorted order. Each item of is at most each item of and at most each item of . The part is not changed.
At the start, and the part is empty, so (M) is true. The first equation gives , so . A write to therefore never changes an item at an index of or more, before it is read.
In a step of line L8, both and exist. By (M) and because both parts are sorted, the smallest item that is not yet placed is or . Line L9 or line L10 writes the smaller one to , so is sorted and the third statement stays true. Line L11 and the update of or keep the first equation. If both items are equal, line L9 takes , which comes from the left half.
The loop of line L8 stops when or . If , then and the loop of line L12 does not run. The items are in place: they are not changed, they are sorted, and by (M) they are at least each placed item. If , the loop of line L12 copies to in order, and each of these items is at least each placed item. In both cases is sorted, and it holds all of and all of the old right half, so it holds .
Theorem. After MERGE-SORT, the part is sorted and holds . No other item of changes.
Proof. By strong induction on . If , line L1 returns, and a part with at most one item is sorted. If , line L2 gives , so both calls of lines L3 and L4 have a shorter range. By the induction hypothesis, they sort and , and each call changes only its own part. The lemma then shows that line L5 makes sorted, with the items of .
Stability. Equal items in the same half keep their order by the induction hypothesis. For equal items in different halves, line L9 places the item of the left half first.