Convert min Heap to max Heap in C++


In this tutorial, we will be discussing a program to convert min heap to max heap.

For this we will be provided with the array representation of the min heap. Our task is to convert that given min heap to max heap in O(n) time complexity.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//converting a given subtree into a heap
void convert_arrayheap(int arr[], int i, int n){
   int l = 2*i + 1;
   int r = 2*i + 2;
   int largest = i;
   if (l < n && arr[l] > arr[i])
      largest = l;
   if (r < n && arr[r] > arr[largest])
      largest = r;
   if (largest != i){
      swap(arr[i], arr[largest]);
      convert_arrayheap(arr, largest, n);
   }
}
//finally building the max heap
void convert_maxheap(int arr[], int n){
   //heapify all the node elements
   for (int i = (n-2)/2; i >= 0; --i)
   convert_arrayheap(arr, i, n);
}
//printing the array
void printArray(int* arr, int size){
   for (int i = 0; i < size; ++i)
   printf("%d ", arr[i]);
}
int main(){
   int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   printf("Min Heap array : ");
   printArray(arr, n);
   convert_maxheap(arr, n);
   printf("\nMax Heap array : ");
   printArray(arr, n);
   return 0;
}

Output

Min Heap array : 3 5 9 6 8 20 10 12 18 9
Max Heap array : 20 18 10 12 9 9 3 5 6 8

Updated on: 22-Jan-2020

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements