Proofs: Sift-up
These are the human proofs of Sift-up, at full length.
Sift-up restores the heap property full
This proof shows: correctness, termination.
Write for . An edge is a pair with . The edge is right when . The array is a min-heap when all edges are right.
Theorem. Let and satisfy (H1) every edge with is right, and (H2) if , then for each child of . Then SIFT-UP ends after at most iterations. At the end, is a min-heap, it is a permutation of the input, and only the cells on the path from the input to the root have changed.
Proof. We show that this invariant holds before each test of line L1:
(I) (H1) and (H2) hold for the current value of . The array is a permutation of the input, and each changed cell is on the path from the input index to the root.
Initialization. Before the first test, (I) is the hypothesis of the theorem, and no cell has changed.
Maintenance. Assume (I) and . Line L2 sets . If line L3 finds , the procedure returns; we treat that case under termination. Else . Write and before line L4, so . After line L4, and . We check each edge that has or as an end. All other edges keep both values, so they stay as they were.
- The edge : , so it is right.
- An edge for a child of : before the swap, (H2) gave . Now , so the edge is right.
- The edge for the other child of , if it exists: before the swap the edge was right by (H1), because , so . Now , so it is right.
- The edge , if : this is the one edge that (H1) for the new index leaves out.
So each edge whose child is not is right, which is (H1) for . For (H2) with : the edge was right before the swap by (H1), because , so . The children of are now , with value , and , with by step 3. Both are at least , which did not change. So (H2) holds for . A swap keeps the multiset of the items, and is on the path from the input index to the root. Line L5 sets , so (I) holds before the next test.
Termination. Each iteration that does not return replaces by . For , , because . So the depth drops by exactly 1 in each such iteration, and it is never negative. Hence there are at most iterations, counted from the input .
The procedure stops in one of two ways. At line L3, , so the edge that (H1) leaves out is right too, and all edges are right. At line L1 with , no edge has the child , so (H1) already covers all edges. In both cases is a min-heap, and by (I) it is a permutation of the input that changed only on the path.
HEAP-INSERT. Before line L7, all edges of are right. After line L7 the new index has no children, and all edges except are old edges. So (H1) and (H2) hold for , and the theorem applies to the call of line L8.
Decrease-key. If is a min-heap and the value at is lowered from to , then each edge stays right, because , and gives (H2). So the theorem applies to SIFT-UP.