Proofs: Heap extract-max
These are the human proofs of Heap extract-max, at full length.
HEAP-EXTRACT-MAX returns a largest key and leaves a max-heap full
This proof shows: correctness, termination.
Write for and . An edge is a pair with , and it holds when . Let be the set of children of that exist, a subset of of indices at most .
Lemma (MAX-HEAPIFY). Let and assume
(D) each edge with holds, and if , then for each .
Then MAX-HEAPIFY stops after at most swaps, only permutes the keys of , and afterwards each edge holds.
Proof. We show that (D) is an invariant of the loop of line L7 for the current . It holds at the start. Lines L8 to L10 set to an index of a largest key among and for : line L9 tests the left child against , line L10 tests the right child against the larger of the two, and each test is made only for a child that exists.
If , then for each , so the edges out of hold, and with (D) every edge holds. Line L11 returns.
Else let and , so , and for the other child of if it exists. Line L12 swaps them. Then the edge holds because , the edge holds because , and the edge , if , holds because (D) gave . Other edges with an end at or are the edges out of , which (D) for the new value excludes. For the second part of (D) at : its parent now holds , and each child of had before the swap, because the edges out of were not excluded. So (D) holds for the new .
Each swap moves one level down. The subtree of the first has height , so there are at most that many swaps, and then the next iteration finds , at the latest at a leaf. The only changes are swaps.
Theorem. Let be a max-heap with . Then HEAP-EXTRACT-MAX returns a largest key of , and afterwards is a max-heap whose multiset of keys is the old one with one copy of the returned key removed. With it reports an error. It stops.
Proof. Line L1 handles . Let . Each has the root as an ancestor, and the edges on the path from to hold, so by a chain of inequalities. So , saved at line L2, is a largest key. Lines L3 and L4 write the old into the root and set , so the keys of are the old keys with one copy of removed (if , the array is empty and the claim holds). Each edge with and joins two cells other than the root, whose keys did not change, so it holds; and the root has no parent. So (D) holds with , and by the lemma, after line L5 each edge holds and the keys were only permuted. Line L6 returns .