Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Putting Items into a Binary Heap

There are two requirements which must be satisfied when an item is inserted in a binary heap. First, the resulting tree must have the correct shape. Second, the tree must remain heap-ordered. Figure gif illustrates the way in which this is done.

Since the resulting tree must be a complete tree, there is only one place in the tree where a node can be added. I.e., since the bottom level must be filled from left to right, the node node must be added at the next available position in the bottom level of the tree as shown in Figure gif (a).

   figure24897
Figure: Inserting an Item into a Binary Heap

In this example, the new item to be inserted has the key 2. Note that we cannot simply drop the new item into the next position in the complete tree because the resulting tree is no longer heap ordered. Instead, the hole in the heap is moved toward the root by moving items down in the heap as shown in Figure gif (b) and (c). The process of moving items down terminates either when we reach the root of the tree or when the hole has been moved up to a position in which when the new item is inserted the result is a heap.

Program gif gives the code for inserting an item in a binary heap. The Enqueue member function of the BinaryHeap class takes as its lone argument a reference to the item to be inserted in the heap. If the priority queue is full an exception is thrown. Otherwise, the item is inserted as described above.

   program25217
Program: BinaryHeap Class Enqueue Member Function Definition

The implementation of the algorithm is actually remarkably simple. Lines 6-11 move the hole in the heap up by moving items down. When the loop terminates, the new item can be inserted at position i. Therefore, the loop terminates either at the root, i=1, or when the key in the parent of i, which is found at position tex2html_wrap_inline66352, is smaller than the item to be inserted.

Notice too that a good optimizing compiler will recognize that the subscript calculations involve only division by two. Therefore, the divisions can be replaced by bitwise right shifts which usually run much more quickly.

Since the depth of a complete binary tree with n nodes is tex2html_wrap_inline66396, the worst case running time for the Enqueue operation is

displaymath66382

where tex2html_wrap_inline64816 is the time required to compare to objects. If

displaymath66383

the Enqueue operation is simply tex2html_wrap_inline59891 in the worst case.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.