Algorithm Search⌘K

Proofs: Heap increase-key

These are the human proofs of Heap increase-key, at full length.

HEAP-INCREASE-KEY leaves a max-heap with the key replaced full

This proof shows: correctness, termination.

Write p(j)=⌊j/2⌋p(j) = \lfloor j/2 \rfloor. An edge is a pair (p(j),j)(p(j), j) with 2≤j≤n2 \le j \le n, and it holds when A[p(j)]≥A[j]A[p(j)] \ge A[j]. Let C(i)C(i) be the set of children of ii that exist.

Invariant. Before each test of line L3:

(U) each edge (p(j),j)(p(j), j) with j≠ij \ne i holds, and if i≥2i \ge 2, then A[p(i)]≥A[c]A[p(i)] \ge A[c] for each c∈C(i)c \in C(i).

Initialization. Let aa be the key at ii before line L2, so k≥ak \ge a by line L1. Before line L2 each edge held. Line L2 changes only the cell ii. The edges (i,c)(i, c) held with aa, so A[c]≤a≤kA[c] \le a \le k, and they still hold. The edges not touching ii are unchanged. The edge (p(i),i)(p(i), i) is the one that (U) excludes. If i≥2i \ge 2, the old edges give A[p(i)]≥a≥A[c]A[p(i)] \ge a \ge A[c] for each c∈C(i)c \in C(i). So (U) holds.

Maintenance. Let the test be true, so i≥2i \ge 2 and, with q=p(i)q = p(i), x=A[q]<A[i]=yx = A[q] < A[i] = y. Line L4 swaps them, so A[q]=yA[q] = y and A[i]=xA[i] = x. We check the edges with an end at qq or ii, except the edge into qq, which (U) for the new i=qi = q excludes.

  • The edge (q,i)(q, i): y≥xy \ge x.
  • The edges (i,c)(i, c) for c∈C(i)c \in C(i): the second part of (U) gave x=A[q]≥A[c]x = A[q] \ge A[c], and A[c]A[c] did not change.
  • The edge (q,t)(q, t) for the other child tt of qq: it held before, so A[t]≤x<yA[t] \le x < y.

So after line L5 each edge except the one into the new ii holds. For the second part of (U) at the new i=q≥2i = q \ge 2: the edge (p(q),q)(p(q), q) held before the swap, because it is not the edge into the old ii, so A[p(q)]≥xA[p(q)] \ge x; and the children of qq now hold xx and A[t]≤xA[t] \le x. So (U) holds.

Termination. Each iteration halves ii, so the loop stops after at most ⌊lg⁡i⌋\lfloor \lg i \rfloor iterations. When it stops, either i=1i = 1, and the root has no edge into it, or A[p(i)]≥A[i]A[p(i)] \ge A[i], so the excluded edge holds too. With (U), each edge holds.

Theorem. If A[1…n]A[1 \ldots n] is a max-heap, 1≤i≤n1 \le i \le n and k≥A[i]k \ge A[i], then after HEAP-INCREASE-KEY(A,i,k)(A, i, k) the array is a max-heap, and its multiset of keys is the old one with one copy of the old A[i]A[i] replaced by kk. If k<A[i]k < A[i], it reports an error and changes nothing.

Proof. Line L1 handles k<A[i]k < A[i]. Else, by the invariant and termination, each edge holds at the end. Line L2 replaced one key by kk, and the loop only swaps. ■\blacksquare

Back to Heap increase-key