Proofs: Heap delete
These are the human proofs of Heap delete, at full length.
HEAP-DELETE removes the key at index i and leaves a max-heap full
This proof shows: correctness, termination.
Write for after line L4, so , and . An edge is a pair with , and it holds when . Let be the set of children of with index at most .
We use two lemmas whose proofs are on other pages, for a max-heap in place of a min-heap.
- Lemma U (sift-up). If each edge with holds, and, when , for each , then SIFT-UP stops after at most swaps and afterwards each edge holds. This is the invariant proof of heap increase-key, whose loop is lines L9 to L11.
- Lemma D (sift-down). If each edge with holds, and, when , for each , then MAX-HEAPIFY stops after at most swaps and afterwards each edge holds. This is the lemma of heap extract-max, whose loop is lines L12 to L17.
Both only swap keys.
Theorem. Let be a max-heap and . Then HEAP-DELETE returns the old , and afterwards is a max-heap whose multiset of keys is the old one with one copy of the old removed. It stops. An index out of range gives an error.
Proof. Line L1 handles a bad index. Let be the old and the old . Lines L2 to L4 save , write into the cell and set . The keys of are now the old keys with one copy of removed: if , the cell was dropped; else the cell lost and got , and the cell , which held , was dropped.
Case . Then , line L5 skips the repair, and is the old heap without its last cell. Each of its edges is an old edge, so it holds.
Case . Each edge with no end at joins two unchanged cells, so it holds. The edges with an end at are when , and for . For each we have , because the edge held before, and if , then , because the edge held before.
- Sub-case: line L6 calls SIFT-UP, so and . Then for each , , so each edge holds. Each edge with holds, and for each . So the hypothesis of Lemma U holds, and afterwards each edge holds.
- Sub-case: line L7 calls MAX-HEAPIFY, so or . Then the edge holds if , and each edge with holds. If , for each . So the hypothesis of Lemma D holds, and afterwards each edge holds.
In each case the sift only swaps, so the multiset of keys stays the one above, and the sift stops by its lemma. Line L8 returns .