Question

Consider the following array of elements

⟨89,19,50,17,12,15,2,5,7,11,6,9,100⟩\langle 89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9, 100 \rangle

The minimum number of interchanges needed to convert it into a max-heap is

Choose one option
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 i=⌊13/2⌋=6i = \lfloor 13/2 \rfloor = 6 down to 11.

Trace bottom-up max-heapify:

  1. i=6i = 6: A[6]=15A[6] = 15. Children are A[12]=9A[12] = 9 and A[13]=100A[13] = 100. The maximum child is 100100. Swap A[6]A[6] and A[13]A[13] (1st interchange).
    Array at i=6i=6 becomes 100100, and A[13]A[13] becomes 1515.
  2. i=5i = 5: A[5]=12A[5] = 12. Children are A[10]=11,A[11]=6A[10] = 11, A[11] = 6. Both ≤12\le 12. No interchange.
  3. i=4i = 4: A[4]=17A[4] = 17. Children are A[8]=5,A[9]=7A[8] = 5, A[9] = 7. Both ≤17\le 17. No interchange.
  4. i=3i = 3: A[3]=50A[3] = 50. Children are A[6]=100,A[7]=2A[6] = 100, A[7] = 2. Maximum child is 100100. Swap A[3]A[3] and A[6]A[6] (2nd interchange).
    A[3]A[3] becomes 100100, A[6]A[6] becomes 5050. Check subtree at i=6i=6: children are 99 and 1515, both ≤50\le 50. No further swap.
  5. i=2i = 2: A[2]=19A[2] = 19. Children are A[4]=17,A[5]=12A[4] = 17, A[5] = 12. Both ≤19\le 19. No interchange.
  6. i=1i = 1: A[1]=89A[1] = 89. Children are A[2]=19,A[3]=100A[2] = 19, A[3] = 100. Maximum child is 100100. Swap A[1]A[1] and A[3]A[3] (3rd interchange).
    A[1]A[1] becomes 100100, A[3]A[3] becomes 8989. Check subtree at i=3i=3: children are A[6]=50,A[7]=2A[6] = 50, A[7] = 2, both ≤89\le 89. Subtree satisfied.

The total number of interchanges needed is exactly 3 (Option D).

Final answer

D

Common trap

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.