Proofs: Balance Sort
These are the human proofs of Balance Sort, at full length.
Balance Sort sorts stably, and keeps every bucket balanced across the disks full
This proof shows: correctness.
We use the line numbers of the pseudocode. All items carry their input position, and ties on the key are broken by the position, so all items are distinct and their order is a total order. A sort of the items in this order is a stable sort of the keys.
Correctness
Lemma 1 (buckets). Let be the splitters, and . Lines L6 and L9 put each item of in exactly one bucket , the one with . Every item of bucket is smaller than every item of bucket for .
Proof. The intervals for are disjoint and cover all values. A write step of line L7 either places a ready block or keeps it ready, and line L9 repeats write steps until no block is ready, so every item is written to its bucket once. If is in bucket and in bucket , then .
Lemma 2 (progress). If , then and every bucket has fewer than items.
Proof. The first memoryload has items, which is at least because . The step of the sample is , and for . So this load has at least items and gives at least 2 sample items. The rank is at most the sample size, so . The splitter has rank in the sample, so the sample item of rank 1 is smaller than and lies in bucket 0. So every bucket misses . Bucket 0 misses , which is an item of .
Theorem 1. BALANCE-SORT returns the items of in sorted order.
Proof. By strong induction on . For , line L1 sorts in memory. Else, by Lemma 2, each bucket is smaller, so by induction line L9 sorts it. By Lemma 1, the buckets in order, each sorted, form the sorted file.
Balance
Fix a bucket , and write for and for . The invariant is for all .
Lemma 3. Before each placement for bucket , more than disks are allowed for , not counting the disks already used in the same write step.
Proof. Let . A disk is not allowed if , that is, . If disks are not allowed, then , because . So , and more than disks are allowed.
Lemma 4 (invariant). After each placement, for all buckets and disks .
Proof. At the start all counts are 0. A placement of a block of on an allowed disk makes at most , which is for the new total . The other counts of do not change, and does not decrease. The counts of the other buckets do not change.
Theorem 2. Each write step places at least blocks, where is the number of ready blocks at its start. At the end of the pass, each bucket of blocks can be read in at most parallel reads.
Proof. Suppose that a write step has placed blocks when it looks at the next ready block, of bucket . Then disks are used. By Lemma 3, more than disks are allowed for , so at least one of them is unused, and line L7 places the block. So the step places blocks as long as fewer than are placed and ready blocks remain. For the second part, a parallel read takes one block from each disk, so a bucket can be read in steps, which is at most by Lemma 4.