The dequeueMin method removes from a priority queue the item having the smallest key. In order to remove the smallest item, it needs first to be located. Therefore, the dequeueMin operation is closely related to findMin.
The smallest item is always at the root of a min heap. Therefore, the findMin operation is trivial. Program gives the code for the findMin method of the BinaryHeap class. Assuming that no exception is thrown, the running time of findMin is clearly O(1).
Program: BinaryHeap class findMin method.
Since the bottom row of a complete tree is filled from left to right as items are added, it follows that the bottom row must be emptied from right to left as items are removed. So, we have a problem: The datum to be removed from the heap by dequeueMin is in the root, but the node to be removed from the heap is in the bottom row.
Figure (a) illustrates the problem. The dequeueMin operation removes the key 2 from the heap, but it is the node containing key 6 that must be removed from the tree to make it into a complete tree again. When key 2 is removed from the root, a hole is created in the tree as shown in Figure (b).
Figure: Removing an item from a binary heap.
The trick is to move the hole down in the tree to a point where the left-over key, in this case the key 6, can be reinserted into the tree. To move a hole down in the tree, we consider the children of the empty node and move up the smallest key. Moving up the smallest key ensures that the result will be a min heap.
The process of moving up continues until either the hole has been pushed down to a leaf node, or until the hole has been pushed to a point where the left over key can be inserted into the heap. In the example shown in Figure (b)-(c), the hole is pushed from the root node to a leaf node where the key 6 is ultimately placed is shown in Figure (d).
Program gives the code for the dequeueMin method of the BinaryHeap class. This method implements the deletion algorithm described above. The main loop (lines 15-25) moves the hole in the tree down by moving up the child with the smallest key until either a leaf node is reached or until the hole has been moved down to a point where the last element of the array can be reinserted.
Program: BinaryHeap class dequeueMin method.
In the worst case, the hole must be pushed from the root to a leaf node. Each iteration of the loop makes at most two object comparisons and moves the hole down one level. Therefore, the running time of the dequeueMin operation is
where is the number of items in the heap. If and , the dequeueMin operation is simply in the worst case.