Proofs: External merge sort
These are the human proofs of External merge sort, at full length.
External merge sort sorts the file stably and does at most the stated number of I/Os full
This proof shows: correctness.
We use the line numbers of the pseudocode. A stable sort of a sequence is the sequence of its items in non-decreasing order, where equal items keep their order in . We write for it. We assume , so .
Lemma 1 (merge). Let be sequences, and let be their concatenation. A merge of the runs that outputs the smallest head, and on equal heads the head of the run with the smallest index, outputs .
Proof. Each run is sorted, so the head of run is its smallest item that is not yet output. So each output item is a minimum of the items that are not yet output, and the output is non-decreasing. Each item is output one time, so the output is a permutation of in non-decreasing order. Take two equal items and , where comes before in . If both are in the same part , then comes before in , and the merge outputs the items of one run in their order. If is in and is in with , consider the step that outputs . At this step is the head of run . If were not yet output, the head of run would satisfy . If , the merge would not output . If , the tie rule would output first. So is output before . Both cases give the order of .
Invariant. At each test of line L6, there are consecutive parts of , with , such that . If , each part is not empty.
Initialization. Lines L3 to L5 cut into pieces of consecutive items from left to right, the last piece possibly shorter, and append the stable sort of each piece to in this order. So the invariant is true with the pieces as the parts.
Maintenance. Line L8 cuts into groups of consecutive runs, from left to right. A group of runs becomes one run. If , line L9 keeps it, and it is . If , Lemma 1 shows that line L10 makes . The new parts are consecutive, in order, and their concatenation is . So after line L11 the invariant is true again.
Termination. If at line L6, the pass makes runs. Because , . So drops by at least 1 in each pass, and the loop stops after at most passes.
Theorem. EXTERNAL-MERGE-SORT returns .
Proof. If , line L3 does nothing, is empty, and line L12 returns an empty file. If , the loop stops with , and by the invariant the one run is with .
The I/O count. Let and , and assume that divides and . Run formation reads and writes each piece. All pieces except the last have items, a multiple of , so the pieces use blocks in total, and run formation costs I/Os. By the invariant, in each pass all runs except the last hold a union of full pieces, so their lengths are multiples of , and the runs use blocks in total. A pass reads and writes each run of a group with two or more runs, and does no I/O for a group of one run, so a pass costs at most I/Os. For integers and , . By induction, after pass there are runs. This is 1 exactly when , so the number of passes is . The total is at most .