Proofs: K-way merge
These are the human proofs of K-way merge, at full length.
The k-way merge outputs the stable sort of its runs full
This proof shows: correctness.
We use the line numbers of the pseudocode. Let be the runs at the start, each sorted in non-decreasing order, and let be the total number of items. Label each item with its run number and its position in the run. The stable order of the items is the order by key, then by , then by . The stable sort of the items is the list of all items in the stable order. During the merge, write for the part of run that is not yet removed. Each is a suffix of the original run, so it is sorted.
Invariant. At each test of line L5:
- lists the removed items in the stable order.
- holds exactly one pair for each with not empty, and this pair is , where is the head of .
- Each item of comes before each item that is still in some , in the stable order.
Initialization. Lines L2 and L3 add for each run that is not empty, and no other pair. Line L4 makes empty. So parts 1 and 3 are true with no removed items, and part 2 is true.
Maintenance. Assume the invariant and that is not empty. Let be the minimum of at line L6, in the order by key, then by run number. We show that , which is , is the first remaining item in the stable order. Take any remaining item in some . Because is sorted, its head satisfies , and is in by part 2. If has a smaller key than , then , and is smaller than , which is false. So the key of is at least the key of . If the keys are equal and , then , so , and the minimum rule gives . If and , then comes after the head in run , so it has a larger position. In each case comes before in the stable order.
Line L7 appends to and removes it from . By part 3 and the result above, is still in the stable order, and comes before each remaining item, so parts 1 and 3 stay true. Only changed. If is not empty, line L8 puts the pair of its new head in the place of . If is empty, line L9 removes . In both cases part 2 stays true.
Termination. Each iteration removes exactly one item from the runs, and the runs hold items at the start. By part 2, is empty exactly when all runs are empty. So the loop runs exactly times.
Theorem. K-WAY-MERGE returns the stable sort of the items of .
Proof. When the loop stops, all items are removed, and by part 1, lists them in the stable order. Line L10 returns . A list in the stable order is non-decreasing by key, and equal keys come in the order of their runs and of their positions.