Proofs: Balanced multiway merge sort
These are the human proofs of Balanced multiway merge sort, at full length.
Balanced merge sort sorts stably in ceil(log_P S) passes full
This proof shows: correctness.
We use the line numbers of the pseudocode. Let . Let be the runs made by line L4, in this order, and let be the part of that run came from. So and is the stable sort of . For a sequence , write for its stable sort.
Lemma (merge). If are sequences and the merge of takes the run with the smaller index on equal keys, the result is .
This is Lemma 1 of the proof page of external merge sort; the same proof applies.
Invariant. At each test of line L5 there are a number and consecutive parts of , with , such that for each the run is the run at index of tape , and the tapes hold no other runs.
Initialization. Line L4 writes run to tape , and it is the -th run written to that tape, because the runs with are exactly in number. So the invariant holds with and .
Maintenance. In iteration of line L7, the tapes that still have a run at index are those with , so line L8 merges the runs for , in the order of , which is the order of . By the lemma, the result is with . The loop of line L7 runs for . Line L8 writes to , and it is the -th run written to that tape, by the same count as in the initialization. The parts are consecutive and their concatenation is . After line L9 renames to , the invariant holds with and the parts .
Termination and the pass count. The loop of line L5 runs while , and a pass maps to . For and , , so the loop stops. For integers , , so after passes . This is 1 exactly when . So for the number of passes is .
Theorem. BALANCED-MERGE-SORT returns on tape .
Proof. If , there are no runs, and the result is empty. Else the loop stops with , and by the invariant the only run is with , at index 0 of tape .