Data Structures and Algorithms
A max-heap, in which each parent's value is at least as large as its children's, is stored in an array with the root at a[0]. 45 is added to the heap 50, 30, 40, 10, 20, 35 by placing it at the end and then swapping it with its parent as long as it is larger than the parent. What is the resulting array?
- A50, 30, 40, 10, 20, 35, 45
- B45, 30, 50, 10, 20, 35, 40
- C50, 30, 45, 10, 20, 35, 40
Show answer and explanation
Answer: C. 50, 30, 45, 10, 20, 35, 40
45 is placed at a[6], whose parent is a[(6−1) ÷ 2] = a[2] = 40. Since 45 > 40, they are swapped and 45 moves to a[2]. Its next parent, a[0] = 50, is larger than 45, so the process stops, giving 50, 30, 45, 10, 20, 35, 40. Swaps happen at most as many times as the height of the tree, so insertion takes O(log n), and removing the maximum is also O(log n). For this reason, binary heaps are commonly used to implement priority queues.
- A. It has only been placed at the end; it was not swapped even though it is larger than its parent 40.
- B. This moves 45 all the way to the root, although it is smaller than the root 50.
- C. Correct. After swapping with 40, it stops because its parent 50 is larger.