Heap as array: descendItem
Algorithmic problem: Heap as array: descendItem
Prerequisites:
Type of algorithm: loop
Auxiliary data: A natural number
Abstract view
Invariant: After
.- The parent's key and its parent's keys of the current heap item
identified by are smaller than the key .
Variant:
increases each step and points to a valid position within the heap that is at a lower level than before.
Break condition:
Induction basis
Abstract view:
- Set
to the positions of the heap item to be descended.
Implementation:
Proof: Obvious.
Induction step
Abstract view:
- Let
denote the heap item at the position . - If the existing children have higher or equal keys than
, terminate algorithm. - Let
denote the left child heap item of and the right one. - If the left child has a lower key than the right one:
- Swap the left child with the parent heap item
. - Set
to the position of the child .
- Swap the left child with the parent heap item
- Otherwise:
- Swap the right child with the parent heap item
. - Set
to the position of the child .
- Swap the right child with the parent heap item
Implementation:
- If
, terminate algorithm and- If
:- Call
- Call
- Otherwise:
- Call
- Call
Correctness: If the break condition holds the algorithm is obviously correct, as we already restored the heap property. So consider the case where we have at least one child and its key is smaller than from
Complexity
Statement: The asymptotic complexity is in
Proof: Follows immediately from the fact that the height of the heap tree is in