Open In App

Convert Min Heap to Max Heap

Last Updated : 17 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array representation of min Heap, convert it to max Heap.

Examples: 

Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}

               3
            /     \
          5       9
        /   \    /  \
      6     8  20   10
    /  \   /
12   18 9 

Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8}

           20
         /    \
      18      10
     /    \    /  \
  12     9  9    3
 /  \   /
5    6 8 

Input: arr[] = {3, 4, 8, 11, 13}
Output:  arr[] = {13, 11, 8, 4, 3}
 

Approach: To solve the problem follow the below idea:

The idea is, simply build Max Heap without caring about the input. Start from the bottom-most and rightmost internal node of Min-Heap and heapify all internal nodes in the bottom-up way to build the Max heap.

Follow the given steps to solve the problem:

  • Call the Heapify function from the rightmost internal node of Min-Heap
  • Heapify all internal nodes in the bottom-up way to build max heap
  • Print the Max-Heap

Algorithm: Here’s an algorithm for converting a min heap to a max heap:

  1. Start at the last non-leaf node of the heap (i.e., the parent of the last leaf node). For a binary heap, this node is located at the index floor((n – 1)/2), where n is the number of nodes in the heap.
  2. For each non-leaf node, perform a “heapify” operation to fix the heap property. In a min heap, this operation involves checking whether the value of the node is greater than that of its children, and if so, swapping the node with the smaller of its children. In a max heap, the operation involves checking whether the value of the node is less than that of its children, and if so, swapping the node with the larger of its children.
  3. Repeat step 2 for each of the non-leaf nodes, working your way up the heap. When you reach the root of the heap, the entire heap should now be a max heap.

Below is the implementation of the above approach:

C




// C program to convert min Heap to max Heap
 
#include <stdio.h>
 
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// to heapify a subtree with root at given index
void MaxHeapify(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]);
        MaxHeapify(arr, largest, N);
    }
}
 
// This function basically builds max heap
void convertMaxHeap(int arr[], int N)
{
    // Start from bottommost and rightmost
    // internal node and heapify all internal
    // nodes in bottom up way
    for (int i = (N - 2) / 2; i >= 0; --i)
        MaxHeapify(arr, i, N);
}
 
// A utility function to print a given array
// of given size
void printArray(int* arr, int size)
{
    for (int i = 0; i < size; ++i)
        printf("%d ", arr[i]);
}
 
// Driver's code
int main()
{
    // array representing Min Heap
    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);
 
    // Function call
    convertMaxHeap(arr, N);
 
    printf("\nMax Heap array : ");
    printArray(arr, N);
 
    return 0;
}


C++




// A C++ program to convert min Heap to max Heap
 
#include <bits/stdc++.h>
using namespace std;
 
// to heapify a subtree with root at given index
void MaxHeapify(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]);
        MaxHeapify(arr, largest, N);
    }
}
 
// This function basically builds max heap
void convertMaxHeap(int arr[], int N)
{
    // Start from bottommost and rightmost
    // internal node and heapify all internal
    // nodes in bottom up way
    for (int i = (N - 2) / 2; i >= 0; --i)
        MaxHeapify(arr, i, N);
}
 
// A utility function to print a given array
// of given size
void printArray(int* arr, int size)
{
    for (int i = 0; i < size; ++i)
        cout << arr[i] << " ";
}
 
// Driver's code
int main()
{
    // array representing Min Heap
    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);
 
    // Function call
    convertMaxHeap(arr, N);
 
    printf("\nMax Heap array : ");
    printArray(arr, N);
 
    return 0;
}


Java




// Java program to convert min Heap to max Heap
 
class GFG {
    // To heapify a subtree with root at given index
    static void MaxHeapify(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] and arr[largest]
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;
            MaxHeapify(arr, largest, N);
        }
    }
 
    // This function basically builds max heap
    static void convertMaxHeap(int arr[], int N)
    {
        // Start from bottommost and rightmost
        // internal node and heapify all internal
        // nodes in bottom up way
        for (int i = (N - 2) / 2; i >= 0; --i)
            MaxHeapify(arr, i, N);
    }
 
    // A utility function to print a given array
    // of given size
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; ++i)
            System.out.print(arr[i] + " ");
    }
 
    // driver's code
    public static void main(String[] args)
    {
        // array representing Min Heap
        int arr[] = { 3, 5, 9, 6, 8, 20, 10, 12, 18, 9 };
        int N = arr.length;
 
        System.out.print("Min Heap array : ");
        printArray(arr, N);
 
        // Function call
        convertMaxHeap(arr, N);
 
        System.out.print("\nMax Heap array : ");
        printArray(arr, N);
    }
}
 
// Contributed by Pramod Kumar


Python3




# A Python3 program to convert min Heap
# to max Heap
 
# to heapify a subtree with root
# at given index
 
 
def MaxHeapify(arr, i, N):
    l = 2 * i + 1
    r = 2 * i + 2
    largest = i
    if l < N and arr[l] > arr[i]:
        largest = l
    if r < N and arr[r] > arr[largest]:
        largest = r
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        MaxHeapify(arr, largest, N)
 
# This function basically builds max heap
 
 
def convertMaxHeap(arr, N):
 
    # Start from bottommost and rightmost
    # internal node and heapify all
    # internal nodes in bottom up way
    for i in range(int((N - 2) / 2), -1, -1):
        MaxHeapify(arr, i, N)
 
# A utility function to print a
# given array of given size
 
 
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=" ")
    print()
 
 
# Driver Code
if __name__ == '__main__':
 
    # array representing Min Heap
    arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9]
    N = len(arr)
 
    print("Min Heap array : ")
    printArray(arr, N)
 
    # Function call
    convertMaxHeap(arr, N)
 
    print("Max Heap array : ")
    printArray(arr, N)
 
# This code is contributed by PranchalK


C#




// C# program to convert
// min Heap to max Heap
using System;
 
class GFG {
    // To heapify a subtree with
    // root at given index
    static void MaxHeapify(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] and arr[largest]
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;
            MaxHeapify(arr, largest, n);
        }
    }
 
    // This function basically
    // builds max heap
    static void convertMaxHeap(int[] arr, int n)
    {
        // Start from bottommost and
        // rightmost internal node and
        // heapify all internal nodes
        // in bottom up way
        for (int i = (n - 2) / 2; i >= 0; --i)
            MaxHeapify(arr, i, n);
    }
 
    // A utility function to print
    // a given array of given size
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; ++i)
            Console.Write(arr[i] + " ");
    }
 
    // Driver's Code
    public static void Main()
    {
        // array representing Min Heap
        int[] arr = { 3, 5, 9, 6, 8, 20, 10, 12, 18, 9 };
        int n = arr.Length;
 
        Console.Write("Min Heap array : ");
        printArray(arr, n);
 
        // Function call
        convertMaxHeap(arr, n);
 
        Console.Write("\nMax Heap array : ");
        printArray(arr, n);
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// A PHP program to convert min Heap to max Heap
 
// utility swap function
function swap(&$a,&$b)
{
    $tmp=$a;
    $a=$b;
    $b=$tmp;
}
 
// to heapify a subtree with root at given index
function MaxHeapify(&$arr, $i, $n)
{
    $l = 2*$i + 1;
    $r = 2*$i + 2;
    $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]);
        MaxHeapify($arr, $largest, $n);
    }
}
 
// This function basically builds max heap
function convertMaxHeap(&$arr, $n)
{
    // Start from bottommost and rightmost
    // internal node and heapify all internal
    // nodes in bottom up way
    for ($i = (int)(($n-2)/2); $i >= 0; --$i)
        MaxHeapify($arr, $i, $n);
}
 
// A utility function to print a given array
// of given size
function printArray($arr, $size)
{
    for ($i = 0; $i <$size; ++$i)
        print($arr[$i]." ");
}
 
    // Driver code
 
    // array representing Min Heap
    $arr = array(3, 5, 9, 6, 8, 20, 10, 12, 18, 9);
    $n = count($arr);
 
    print("Min Heap array : ");
    printArray($arr, $n);
 
    convertMaxHeap($arr, $n);
 
    print("\nMax Heap array : ");
    printArray($arr, $n);
 
 
// This code is contributed by mits
?>


Javascript




<script>
// javascript program to convert min Heap to max Heap   
// To heapify a subtree with root at given index
function MaxHeapify(arr , i , n)
{
    var l = 2*i + 1;
    var r = 2*i + 2;
    var 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] and arr[largest]
        var temp = arr[i];
        arr[i] = arr[largest];
        arr[largest] = temp;
        MaxHeapify(arr, largest, n);
    }
}
 
// This function basically builds max heap
function convertMaxHeap(arr , n)
{
    // Start from bottommost and rightmost
    // internal node and heapify all internal
    // nodes in bottom up way
    for (i = (n-2)/2; i >= 0; --i)
        MaxHeapify(arr, i, n);
}
 
// A utility function to print a given array
// of given size
function printArray(arr , size)
{
    for (i = 0; i < size; ++i)
        document.write(arr[i]+" ");
}
 
// driver program
// array representing Min Heap
var arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9];
var n = arr.length;
 
document.write("Min Heap array : ");
printArray(arr, n);
 
convertMaxHeap(arr, n);
 
document.write("<br>Max Heap array : ");
printArray(arr, n);
 
// This code is contributed by 29AjayKumar
</script>


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 

Time Complexity: O(N), for details, please refer: Time Complexity of building a heap
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Convert BST to Max Heap
Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied to all the nodes in the so-converted Max Heap. Examples: In
15+ min read
Convert BST into a Min-Heap without using array
Given a Binary Search Tree, convert it into a Min-Heap containing the same elements in O(n) time. Do this in-place. Input: Binary Search Tree 8 / \ 4 12 / \ / \ 2 6 10 14 Output - Min Heap 2 / \ 4 6 / \ / \ 8 10 12 14 [Or any other tree that follows Min Heap properties and has same keys] If we are allowed to use extra space, we can perform inorder
15+ min read
Convert BST to Min Heap
Given a binary search tree which is also a complete binary tree. The problem is to convert the given BST into a Min Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied to all the nodes, in the resultant converted Min Heap. Examples:
10 min read
Minimize (max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) of three different sorted arrays
Given three sorted arrays A, B, and C of not necessarily same sizes. Calculate the minimum absolute difference between the maximum and minimum number of any triplet A[i], B[j], C[k] such that they belong to arrays A, B and C respectively, i.e., minimize (max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) Examples: Input : A : [ 1, 4, 5, 8, 10 ] B : [ 6
8 min read
Minimum value of "max + min" in a subarray
Given a array of n positive elements we need to find the lowest possible sum of max and min elements in a subarray given that size of subarray should be greater than equal to 2. Examples: Input : arr[] = {1 12 2 2} Output : 4 Sum of 2+2 of subarray [2, 2] Input : arr[] = {10 20 30 40 23 45} Output : 30 Sum of 10+20 of subarray[10, 20] A simple solu
4 min read
Number of odd and even results for every value of x in range [min, max] after performing N steps
Given a number N and the min and max range. Given N values of a and b respectively. The task is to count the number of even/odd results after performing a series of N operations as described below.At every step, calculate: yN = aNyN-1 + bN. Explanation: Step 1: y1 = a1x + b1Step 2: y2 = a2y1 + b2 =&gt; y2 = a2a1x + a2b1 + b2Step 3: y3 = a3y2 + b3 =
15 min read
Article Tags :
Practice Tags :