Let be a priority queue for maintaining a set of elements. Suppose is implemented using a max-heap data structure. The operation extracts and deletes the maximum element from . The operation inserts a new element in . The properties of a max-heap are preserved at the end of each of these operations.
When contains elements, which one of the following statements about the worst case running time of these two operations is
View worked solution
Answer: B
A max-heap containing elements is represented as a nearly complete binary tree of height .
Let's analyze the worst-case time complexity of both operations:
-
:
- To insert a new element, we place it at the next available leaf position (at the end of the array representation) to maintain the structural property of the complete binary tree.
- We then perform a heapify-up (or bubble-up) operation to restore the max-heap property by comparing and swapping the element with its parent.
- In the worst case, the newly inserted element travels from the leaf level to the root. The maximum number of swaps is proportional to the height of the tree, which is .
-
:
- The maximum element is always at the root of the max-heap, which can be accessed in time.
- To delete this element, we replace the root with the last element of the heap and decrease the heap size by 1.
- We then perform a heapify-down (or bubble-down) operation from the root to restore the max-heap property by swapping the element with its larger child.
- In the worst case, this element travels from the root down to a leaf. The maximum number of swaps is proportional to the height of the tree, which is .
Therefore, both and run in time in the worst case.
Free practice · Your answers on this page are not saved.
