Proofs: Oscillating sort
These are the human proofs of Oscillating sort, at full length.
Oscillating sort sorts in ceil(log_P S) merge levels full
This proof shows: correctness.
We use the line numbers of the pseudocode. Let . The work tapes are read backward, so each work tape is a stack of runs: line L4 and line L8 append a run at the end, and line L7 removes the last run. Reading a run backward gives its items in the reverse order. Write for the opposite direction of .
Let be the consecutive parts of items of (the last may be shorter), so that the -th execution of line L4 reads .
Lemma. Let . Suppose that BUILD starts when line L4 has read . Then it returns when line L4 has read , and at that time:
- tape holds its old runs and, after them, one new run, which holds the items of sorted in the direction ;
- every other work tape holds exactly its old runs;
- the recursion below this call has levels of merges.
Proof. By strong induction on .
For , lines L3 and L4 read , sort it in the direction , and append it to . No other tape changes and there is no merge, and .
For , line L5 gives parts with and sum , and distinct tapes , all different from . Line L6 calls BUILD for each with , in the order of . By induction, the call for reads the next parts of , appends to one run with these items sorted in the direction , and leaves every other work tape as it was. In particular, the later calls for do not change , and no call changes . So when line L6 ends, the parts have been read, each holds its old runs followed by , and every other tape is as before.
Line L7 removes from each , which restores , and reads backward, which gives its items sorted in the direction . Line L8 merges these sequences in the direction , so the result is sorted in that direction and holds exactly the items of . It appends the result to . This proves 1 and 2.
For 3, the deepest sub-call is for , and it has levels by induction. The calls with smaller have at most as many levels, because is non-decreasing. Line L8 adds one level, and for integers , because exactly when .
Theorem. OSCILLATING-SORT returns the items of in non-decreasing order, reads once, never rewinds a tape, and makes levels of merges.
Proof. Line L2 calls BUILD with all work tapes empty and nothing read. By the lemma with and , it reads , which is all of , once and in order, and it leaves one run on , which holds all items in non-decreasing order, and all other work tapes empty. All reads of a work tape are backward reads of its last run, and all writes are at its end, so no rewind is needed. Part 3 of the lemma gives the number of levels.