Proofs: Heap construction by insertion
These are the human proofs of Heap construction by insertion, at full length.
BUILD-BY-INSERTION makes the array a max-heap full
This proof shows: correctness, termination.
Write . For , an edge of the prefix is a pair with , and it holds when . The prefix is a max-heap when each of its edges holds. Let be the set of children of that are at most .
Outer invariant. Before the test of line L1 with the value , the prefix is a max-heap, and is a permutation of the input.
Initialization. For , the prefix has no edges.
Maintenance. Fix and consider lines L2 to L5 with . Before each test of line L3, we claim:
(I) each edge of with holds, and if , then for each .
When line L2 sets , the cell has no children in , because . The edges of other than are the edges of , which hold by the outer invariant. The second part holds because is empty. So (I) holds.
Let the test of line L3 be true, so and, with , . Line L4 swaps them. We check the edges with an end at or , except the edge into .
- The edge now holds, since .
- For , the edge : by the second part of (I), , and did not change.
- For the other child of , if : the edge held before, so .
Line L5 sets . So each edge except the one into the new holds. If the new , the edge held before the swap, since it was not the edge into the old ; so , and the children of now hold and . So (I) holds again.
Each iteration halves , so the inner loop stops after at most iterations. When it stops, either , which has no edge into it, or . With (I), each edge of holds, so is a max-heap. The loop only swaps cells, so is still a permutation of the input. This is the outer invariant for .
Termination. The outer loop runs for , and each inner loop stops, as shown. When the outer loop ends, , and the outer invariant says that is a max-heap.
Theorem. For each array with , BUILD-BY-INSERTION stops, and after it is a max-heap that is a permutation of the input. Moreover, after the iteration with the value , the prefix is a max-heap, and the iteration does not read or write a cell beyond .
Proof. The first two claims are the invariant at the end and termination. The last claim holds because the inner loop reads and writes only the cells and with . So the method is online: it can run while the keys arrive.