Find out the number of interchanges needed to convert the given array into a…

2024

Find out the number of interchanges needed to convert the given array into a max-heap. 89,19,50,17,12,15,2,5,7,11,6,9,100

  1. A.

    1

  2. B.

    2

  3. C.

    3

  4. D.

    0

Attempted by 206 students.

Show answer & explanation

Correct answer: C

Concept: A max-heap is a complete binary tree in which every parent node's value is greater than or equal to both of its children's values. The standard bottom-up build-max-heap algorithm converts an arbitrary array into a max-heap by applying the sift-down (heapify) operation starting from the last non-leaf node down to the root, swapping a parent with its larger child wherever the max-heap property is violated at that node.

  1. Heapify at index 6 (value 15): children are index 12 (value 9) and index 13 (value 100). Since 100 > 15, swap positions 6 and 13. (Interchange 1)

  2. Heapify at index 5 (value 12): children are index 10 (value 11) and index 11 (value 6); both are smaller, no swap needed.

  3. Heapify at index 4 (value 17): children are index 8 (value 5) and index 9 (value 7); both are smaller, no swap.

  4. Heapify at index 3 (value 50): children are index 6 (now value 100, after step 1) and index 7 (value 2); since 100 > 50, swap positions 3 and 6. (Interchange 2) Re-check index 6 (now value 50) against its children (9, 15); both smaller, no further swap.

  5. Heapify at index 2 (value 19): children are index 4 (value 17) and index 5 (value 12); both are smaller, no swap.

  6. Heapify at index 1 (value 89): children are index 2 (value 19) and index 3 (now value 100, after step 4); since 100 > 89, swap positions 1 and 3. (Interchange 3) Re-check index 3 (now value 89) against its children (50, 2); both smaller, no further swap.

Cross-check: in the final array 100,19,89,17,12,50,2,5,7,11,6,9,15, every parent satisfies the max-heap property: node1=100 ≥ 19,89; node2=19 ≥ 17,12; node3=89 ≥ 50,2; node4=17 ≥ 5,7; node5=12 ≥ 11,6; node6=50 ≥ 9,15.

Total interchanges = 3.

Explore the full course: Coding For Placement