Skip to content
Official PYQ · 2015

GATE CS 2015 Set 3 Q19 — Binary Heaps

Explain with AI

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
View worked solution

Answer: D

To find the minimum number of interchanges (swaps) required to convert the given array into a max-heap, we first represent the array as a binary tree where the element at index ii has children at indices 2i2i and 2i+12i+1 (using 1-based indexing):

  • Level 0: 8989 (index 1)
  • Level 1: 1919 (index 2), 5050 (index 3)
  • Level 2: 1717 (index 4), 1212 (index 5), 1515 (index 6), 22 (index 7)
  • Level 3: 55 (index 8), 77 (index 9), 1111 (index 10), 66 (index 11), 99 (index 12), 100100 (index 13)

Checking the max-heap property (A[parent]≥A[child]A[parent] \ge A[child]), we find only one violation: the node 1515 at index 6 is smaller than its right child 100100 at index 13.

Since 100100 is the largest element in the entire array, it must eventually reach the root (index 1) of the max-heap. We can achieve this by bubbling up 100100 along its ancestor path:

  1. Swap 1: Swap 100100 (index 13) with its parent 1515 (index 6).
    Array becomes: ⟨89,19,50,17,12,100,2,5,7,11,6,9,15⟩\langle 89, 19, 50, 17, 12, \mathbf{100}, 2, 5, 7, 11, 6, 9, \mathbf{15} \rangle
  2. Swap 2: Swap 100100 (index 6) with its parent 5050 (index 3).
    Array becomes: ⟨89,19,100,17,12,50,2,5,7,11,6,9,15⟩\langle 89, 19, \mathbf{100}, 17, 12, \mathbf{50}, 2, 5, 7, 11, 6, 9, 15 \rangle
  3. Swap 3: Swap 100100 (index 3) with its parent 8989 (index 1).
    Array becomes: ⟨100,19,89,17,12,50,2,5,7,11,6,9,15⟩\langle \mathbf{100}, 19, \mathbf{89}, 17, 12, 50, 2, 5, 7, 11, 6, 9, 15 \rangle

The array now satisfies the max-heap property. The minimum number of interchanges required is 3.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Binary Heaps questions