Given an array representing a min-heap, convert it into a max-heap. The conversion should be done in-place and in linear time.

The idea is simple and inspired by the Heapsort algorithm. The problem looks complex at first glance, but this problem is no different from building a max-heap from an unsorted array. This is a tricky problem! It doesn’t matter whether the given array is a min-heap or not. We can simply build the max-heap from the array by starting from the last internal mode (rightmost, bottom-most node) of the min-heap and Heapify all internal modes in a bottom-up manner to build the max-heap.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The array representation of max-heap is 10 6 8 1 3 4 5

The time complexity of the above solution looks like O(n.log(n)) at first look, but it is the same as the time complexity of building 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 max-heap into min-heap in linear time