Proofs: Shiloach-Vishkin merging
These are the human proofs of Shiloach-Vishkin merging, at full length.
Shiloach-Vishkin merging computes the stable merge full
This proof shows: correctness.
Let be the stable merge of the sorted arrays and : the items in the strict order where comes before if has the smaller key, or the keys are equal and is in and in , or both are in the same array and has the smaller index. A pair is a split if the first items of are and .
Lemma 1. The cuts are splits
Proof. Let be an A-cut, with the number of items of less than . The items before in are , and the items with , which are because is sorted. So is at position , and the first items are those. A B-cut , with the number of items of at most , is the same with the roles swapped: the items before are and the items of at most , which are . The pairs and are splits too.
Lemma 2. Splits form a chain
If and are splits with , then and . Two different splits have different sums .
Proof. The first items of are a prefix of the first items, so is part of and of . If , the two prefixes are the same set, so and .
Lemma 3. Line L4 gives the order
Let and . The number of B-cuts that come before the A-cut in the order of Lemma 2 is , and the number of A-cuts that come before the B-cut is . No A-cut equals a B-cut.
Proof. A B-cut with index comes before the A-cut if and only if is among the first items of , that is, if and only if by Lemma 1. The number of integers with is , and all of them satisfy and , because . The count for a B-cut is the same with the roles swapped. If an A-cut and a B-cut were the same pair , then would not be less than (because only items of are less than ) and would not be at most (because only items of are at most ), which is impossible.
So the place that line L4 gives to a cut is its index among the cuts of its own list plus the number of cuts of the other list before it, which is its index in the sorted order of all cuts. The places are distinct, and is the list of all splits in increasing order.
Lemma 4. Each piece is a merge of two parts
Let and be consecutive in . Then is the stable merge of and , and it holds at most items of and at most items of .
Proof. By Lemma 2, and . The first items of are and , and the first are and . So the items in between are and , in the order of , which on these items is their stable merge. If the part of had more than items, it would contain an index with and , and then the A-cut would be a split strictly between the two consecutive splits, by Lemma 2. The same holds for .
Theorem
SV-MERGE writes the stable merge of and .
Proof. By Lemma 3, lists , all cuts and in increasing order of . The pieces between consecutive splits cover the positions of exactly once, and by Lemma 4 line L7 writes the correct items to each piece.