Given an array representing a max-heap, in-place convert it into the min-heap in linear time.

Practice this problem

The idea is simple and efficient and inspired by the Heapsort algorithm. The idea is to build the min-heap in-place using an array representing the max-heap. In other words, this is a trick question!! We should not be bothered about whether the given array is max-heap or not. The problem is the same as building a min-heap from an unsorted array.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

-2 1 5 9 4 6 7

Java


Download  Run Code

Output:

[-2, 1, 5, 9, 4, 6, 7]

Python


Download  Run Code

Output:

[-2, 1, 5, 9, 4, 6, 7]

The time complexity of the above solution is the same as the building of a heap, i.e., O(n) for an input containing n items. It also requires O(n) implicit space for the call stack.

 
Exercise: Convert min-heap into max-heap in O(n) time