Proofs: Merge path
These are the human proofs of Merge path, at full length.
Merge path computes the stable merge full
This proof shows: correctness.
Let be the stable merge of the sorted arrays and , in which comes before if has a smaller key, or the keys are equal and is in and in , or both are in the same array and has the smaller index.
Lemma 1. Co-ranks exist and are unique
For each with , there is exactly one pair with such that the first items of are and . Moreover .
Proof. The stable order lists the items of in index order, so the items of among the first items of are a prefix , and the same holds for with some . Since there are items in all, , and the pair is fixed by . From , and follows the range of .
Lemma 2. The test on line L4
Let . Then holds exactly when is not among the first items of .
Proof. The bounds give , so exists. The items before in are and the items of with key less than , as items of with equal key come after . So is at position , where is the number of items of less than . It is among the first items when , that is, . Since is sorted, holds exactly when .
Lemma 3. CO-RANK returns the co-rank
Proof. Let be the co-rank of . By Lemma 1, is among the first items of exactly when . So by Lemma 2, for in the search range with , the test on line L4 is false for and true for . The loop keeps the invariant : it holds at the start by Lemma 1; if the test is true at then and setting keeps it; if it is false then and setting keeps it. Each round makes smaller, and the loop ends with . So line L5 returns .
Theorem. MERGE-PATH writes C
Proof. Let , so , and let be the co-rank of . By Lemma 1, and , because the first items of are among the first . The items of are the first items without the first , that is, and . They appear in in the stable order, and the stable order of a subset is the stable order restricted to it, so they appear as the stable merge of these two pieces. Line L8 computes exactly this merge and writes it to . The ranges for different are disjoint and cover , so the processors write without conflicts.