
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Convert BST to Min Heap in C++
- Convert BST to Max Heap in C++
- Max Heap in Java
- Is Max Heap in Python?
- Program to check heap is forming max heap or not in Python
- C++ Program to Implement Min Heap
- C++ Program to Implement Max Heap
- Maximum element in min heap in C++
- Minimum element in a max heap in C++.
- Insertion into a Max Heap in Data Structure
- Deletion from a Max Heap in Data Structure
- K’th Least Element in a Min-Heap in C++
- K-th Greatest Element in a Max-Heap in C++
- Heap Sort
- Print all nodes less than a value x in a Min Heap in C++

Advertisements