Question
Consider the following array of elements
The minimum number of interchanges needed to convert it into a max-heap is
Official answer and solution
- Official answer
- D
- From
- Official GATE 2015 answer key
Solution
Trace the standard heapify algorithm on the array and count the minimum number of swaps needed to satisfy the max-heap property.
The 1-indexed array of 13 elements is:
A = [89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100].
Internal nodes are at indices down to .
Trace bottom-up max-heapify:
- : . Children are and . The maximum child is . Swap and (1st interchange).
Array at becomes , and becomes . - : . Children are . Both . No interchange.
- : . Children are . Both . No interchange.
- : . Children are . Maximum child is . Swap and (2nd interchange).
becomes , becomes . Check subtree at : children are and , both . No further swap. - : . Children are . Both . No interchange.
- : . Children are . Maximum child is . Swap and (3rd interchange).
becomes , becomes . Check subtree at : children are , both . Subtree satisfied.
The total number of interchanges needed is exactly 3 (Option D).
D
Trying to sort the entire array or doing top-down building, which can take extra swaps compared to standard bottom-up build-heap.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 3
- Question
- 29 of 65, printed as CS Q.19
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.