Consider the following array of elements.
The minimum number of interchanges needed to convert it into a max-heap is
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 has children at indices and (using 1-based indexing):
- Level 0: (index 1)
- Level 1: (index 2), (index 3)
- Level 2: (index 4), (index 5), (index 6), (index 7)
- Level 3: (index 8), (index 9), (index 10), (index 11), (index 12), (index 13)
Checking the max-heap property (), we find only one violation: the node at index 6 is smaller than its right child at index 13.
Since 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 along its ancestor path:
- Swap 1: Swap (index 13) with its parent (index 6).
Array becomes: - Swap 2: Swap (index 6) with its parent (index 3).
Array becomes: - Swap 3: Swap (index 3) with its parent (index 1).
Array becomes:
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.
