next up previous contents
Next: Delete max element.- The Up: Implicit Heaps Previous: Implicit Heaps

Insert element.- The siftup procedure

Insertion of a new element into a heap is done in two steps. First the element is inserted in the only place with room for it,- At the bottom of the tree, - And next it is shifted up the tree until the heap property holds. The insertion is trivial, but the siftup deserves extra attention because of its importance for the performance. In C it can be implemented for example in this way.

  program43

Please note the similarity to the inner loop of an insertion sort, the only difference being the update of the index variable c. Siftup simply inserts the last element in the heap into the sequence of elements along the path to the root of the tree. The worst case running time of the siftup operation is tex2html_wrap_inline1231 since this is the depth of the tree.

There is plenty of opportunity for constant factor optimizations in the code presented here. The reader is referred to heaplab for a reasonable efficient implementation.



Jesper Bojesen
Wed Nov 4 15:35:15 MET 1998