Heap as array: descendItem

From Algowiki
Revision as of 23:12, 19 June 2015 by Luedecke (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Algorithmic problem: Heap as array: descendItem

Prerequisites:

Type of algorithm: loop

Auxiliary data: A natural number denoting a position within the heap.

Abstract view

Invariant: After i iterations:

  1. 1n.
  2. The parent's key and its parent's keys of the current heap item h identified by are smaller than the key h.key.

Variant:

  1. increases each step and points to a valid position within the heap that is at a lower level than before.

Break condition:

  1. (2nh.keyTheHeap[2].key)(2+1nh.keyTheHeap[2+1].key)

Induction basis

Abstract view:

  1. Set to the positions of the heap item to be descended.

Implementation:

  1. :=Positions[ID]

Proof: Obvious.

Induction step

Abstract view:

  1. Let h denote the heap item at the position .
  2. If the existing children have higher or equal keys than h, terminate algorithm.
  3. Let leftChild denote the left child heap item of h and rightChild the right one.
  4. If the left child has a lower key than the right one:
    1. Swap the left child with the parent heap item h.
    2. Set to the position of the child leftChild.
  5. Otherwise:
    1. Swap the right child with the parent heap item h.
    2. Set to the position of the child rightChild.

Implementation:

  1. h:=TheHeap[]
  2. If (2nh.keyTheHeap[2].key)(2+1nh.keyTheHeap[2+1].key), terminate algorithm
  3. leftChild:=TheHeap[2] and rightChild:=TheHeap[2+1]
  4. If leftChild.keyrightChild.key:
    1. Call swapItems(,2)
    2. :=2
  5. Otherwise:
    1. Call swapItems(,2+1)
    2. :=2+1

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 h.key. We will further assume that only the subtree with h as its root violates the heap property, to be more exact only the subtree T with h and its immediate children violate the property. Restoring the heap property in such a case requires to swap the minimum item with the root h, this is done in step 4+5. We then have to ensure that the new subtree T with again h as its new root also holds the heap property, this step is done the next iteration and by assigning the position of the swapped child. The other pair of items, namely the earlier children satisfy the heap property because the minimum key was chosen as the new root for T. After at most logn iterations the heap item identified by ID is now a leaf or has two children that fulfill the heap property. Therefore the heap property for the whole tree is restored again.

Complexity

Statement: The asymptotic complexity is in Θ(logn) in the best and worst case.

Proof: Follows immediately from the fact that the height of the heap tree is in Θ(logn).

Further information