Question 1Multiple choiceHeaps & priority queues
The keys 12, 7, 20, 3, 25, 9, 14 are inserted one at a time, in that order, into an initially empty binary max-heap stored in an array with the root at index 0 (the children of index are at indices and ). Each insertion appends the key at the end of the array and sifts it up. What is the array after all seven insertions?
- A.
25, 20, 14, 3, 7, 9, 12
- B.
25, 12, 20, 3, 7, 9, 14
- C.
25, 20, 14, 12, 9, 7, 3
- D.
3, 7, 9, 12, 25, 20, 14
Worked solution
Sift-up compares the new key with its parent at index and swaps while the key is larger than the parent.
- Insert 12: [12].
- Insert 7 at index 1; parent 12 is larger, stop: [12, 7].
- Insert 20 at index 2; parent 12 is smaller, swap: [20, 7, 12].
- Insert 3 at index 3; parent (index 1) is 7, larger, stop: [20, 7, 12, 3].
- Insert 25 at index 4; parent 7 is smaller, swap to index 1; parent 20 is smaller, swap to the root: [25, 20, 12, 3, 7].
- Insert 9 at index 5; parent (index 2) is 12, larger, stop: [25, 20, 12, 3, 7, 9].
- Insert 14 at index 6; parent 12 is smaller, swap to index 2; parent 25 is larger, stop: [25, 20, 14, 3, 7, 9, 12].
Verify the heap property on the result: 25 is at least 20 and 14; 20 is at least 3 and 7; 14 is at least 9 and 12. Every parent dominates its children and the array is a complete tree, so this is a valid max-heap.
Option B is the tempting one: it is what the linear-time bottom-up build-heap produces when applied to the whole array [12, 7, 20, 3, 25, 9, 14] at once. It is also a valid max-heap, but the question specifies repeated insertion, and the two procedures generally give different arrays. Option C is the keys in descending order, which sift-up never produces here (7 and 3 never move once placed). Option D is a min-heap.
[25, 20, 14, 3, 7, 9, 12] (option A).