A max heap is defined as a complete binary tree where every node's value is at least as large as the values of its children. This makes it useful for implementing priority queues, where the highest priority element is always at the root. In this article, we will learn how to implement the max heap data structure in C++.
Implementation of Max Heap in C++
A max heap is a tree-based data structure that satisfies the property of a heap. For every node, i in the max heap other than the root, the value of that node is less than or equal to the value of its parent. Each root node in a max heap can have almost two child nodes where the value of the child nodes must be less than or equal to its parent node. To implement max heap in C++ we use the array data structure. For any node at the index i in the array, the relationship between the parent and child nodes are as follows:
- Index of Parent Node: (i – 1) / 2
- Index of the Left child Node: 2 * i + 1
- Index of the Right child Node: 2 * i + 2
Representation of Max Heap in C++
To represent a max heap efficiently, we can use a class instead of an array because for an array we will have to maintain separate variables to keep track of the size of the heap. Using a class we can encapsulate all of the heap data members and operations within a single class. We will use template instead of a specific data type for the max heap so that it can support multiple types of data. The MaxHeap class will consist of the following data members:
template <typename T>
class MaxHeap {
vector<T> array;
int size;
int capacity;
};
here:
- array: is a std::vector that will store the max heap elements.
- size: denotes the current number of elements present in the max heap.
- capacity: denote the maximum number of elements the max heap can hold.
- T: denotes the type of data the max heap will hold.
The following diagram represents how the index of each element in a max heap is mapped within the array:

Explanation: For the above max heap the root node 15 of the max heap is present at the 0th index of the array,and it's left and right child 5 and 10 are present at 2*i+1 and 2*i+2 indices that is at index 1 and 2. Similary the other nodes of the max heap are represented in the array using the same approach.
Basic Operations Implementation of Max Heap in C++
Following are some basic operations that are required to work with max heap in C++:
Operation Name
| Description
| Time Complexity
| Space Complexity
|
---|
Heapify
| Reorganizes the subtree for a given index of the max heap to ensure that the heap property is maintained properly.
| O(log n)
| O(1)
|
---|
Insert
| Adds a new node to the max heap and ensures that the max heap property is maintained.
| O(log n)
| O(1)
|
---|
Delete Key
| Removes a specific node from the max heap.
| O(log n)
| O(1)
|
---|
Top
| Returns the value of the root node of the max heap.
| O(1)
| O(1)
|
---|
Pop
| Deletes the root node, returns its value, and heapifies the remaining heap
| O(log n)
| O(1)
|
---|
BuildHeap
| Converts an array into max heap.
| O(n)
| O(1)
|
---|
Now let's go through the algorithms for implementing each of these functions for max heap in C++:
Algorithm for Heapify Function
- Find the left child and right child using the 2*i+1 and 2*i+2 formula.
- Identify the largest among the root, left child, and right child.
- If the root node is not the largest, swap it with the child that has the largest value.
- Recursively apply heapify to the affected subtree.
- Repeat until the heap property is restored.
Algorithm for Inserting a Node
- Increase the size of the array by 1 .
- Insert the node to insert in the heap at the end of the array.
- Initialize i to the index of the newly inserted element.
- While i !=root and value of new element greater than it's parent :
- Swap the element with it's parent.
- Update i to the parent index.
Note: You can find the parent index using (index-1)/2 formula.
Algorithm for Deleting a Node
- Traverse the max heap and find the node to you want to delete.
- Store the index of this node.
- Replace the node with the last node in the max heap.
- Decrease the heap size by 1.
- Apply heapify function to the affected index to restore the heap property.
Algorithm for the Top Function
- Check if the heap is empty.
- If not empty, return the root element (maximum element in a max heap).
- If empty, return -1.
Algorithm for the Pop Function
- Check if the heap is empty. If empty return -1.
- Store the root element.
- Replace the root element with the last element in the heap array.
- Reduce the heap size by 1.
- Call the heapify function on the root node to restore the max heap property.
- Return the stored root element.
Algorithm for Build Heap Function
- Start from the last non-leaf node of the max heap and move towards the root node.
- Apply Heapify to each node.
- Continue this process for all nodes until the root node.
- The max heap will be built when all nodes satisfy the max heap property.
C++ Program for Implementing Max Heap
The following program illustrates how we can implement a max heap using array in C++:
C++
// C++ Program for Implementing Max Heap
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Template for MaxHeap
template <typename T>
// Class for MaxHeap
class MaxHeap {
private:
vector<T> array;
int size;
int capacity;
public:
// Constructor to initialize the heap with a given capacity
MaxHeap(int capacity) {
this->size = 0;
this->capacity = capacity;
this->array.resize(capacity);
}
// Function to heapify the node at index i
void heapify(int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && array[left] > array[largest])
largest = left;
if (right < size && array[right] > array[largest])
largest = right;
if (largest != i) {
swap(array[i], array[largest]);
heapify(largest);
}
}
// Function to build a max heap from a given array
void buildHeap(const vector<T>& arr) {
capacity = arr.size();
size = capacity;
array = arr;
// Build heap (rearrange array)
for (int i = (size - 1) / 2; i >= 0; i--) {
heapify(i);
}
}
// Function to insert a new value into the heap
void insert(T value) {
if (size == capacity) {
// Resize the heap if necessary
capacity *= 2;
array.resize(capacity);
}
size++;
int i = size - 1;
array[i] = value;
// Fix the max heap property if it is violated
while (i != 0 && array[(i - 1) / 2] < array[i]) {
swap(array[i], array[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
// Function to get the value of the root node of the max heap
T top() {
if (size <= 0)
// Indicates that the heap is empty
return -1;
return array[0];
}
// Function to remove and return the maximum value from the heap
T pop() {
if (size <= 0)
return -1;
if (size == 1) {
size--;
return array[0];
}
// Store the maximum value, and remove it
T root = array[0];
array[0] = array[size - 1];
size--;
// Heapify the root node after deletion
heapify(0);
return root;
}
// Function to delete a specific key from the heap
void deleteKey(T key) {
// Find the index of the key
int index = -1;
for (int i = 0; i < size; ++i) {
if (array[i] == key) {
index = i;
break;
}
}
// If key is not found, return
if (index == -1) {
cout << "Key not found" << endl;
return;
}
// If the key is found, delete it
// If it's the last element, simply reduce the size
if (index == size - 1) {
size--;
return;
}
// Move the last element to the index of the key to be deleted
array[index] = array[size - 1];
size--;
// Heapify down to maintain heap property
heapify(index);
}
// Function to print the heap
void print() const {
cout << "Max Heap: ";
for (int i = 0; i < size; ++i)
cout << array[i] << " ";
cout << endl;
}
};
int main() {
// Create a MaxHeap with initial capacity of 6
MaxHeap<int> maxHeap(6);
vector<int> arr = {2, 3, 4, 5, 10, 15};
// Build the heap from the array
maxHeap.buildHeap(arr);
// Print the max heap
maxHeap.print();
// Insert a node into the heap
maxHeap.insert(9);
cout << "After inserting 9: " << endl;
maxHeap.print();
// Get the maximum value from the max heap
cout << "Top value: " << maxHeap.top() << endl;
// Delete the root node of the max heap
cout << "Popped value: " << maxHeap.pop() << endl;
cout << "After popping: ";
maxHeap.print();
// Delete a specific value from the max heap
maxHeap.deleteKey(5);
cout << "After deleting the node 5: ";
maxHeap.print();
return 0;
}
OutputMax Heap: 15 10 4 5 3 2
After inserting 9:
Max Heap: 15 10 9 5 3 2 4
Top value: 15
Popped value: 15
After popping: Max Heap: 10 5 9 4 3 2
After deleting the node 5: Max Heap: 10 4 9 2 3
Related Articles
You can also read the following articles to improve your understanding about the heap data structure:
Similar Reads
Heap in C++ STL
The heap data structure can be implemented in a range using STL which provides faster max or min item retrieval, and faster insertion and deletion on sorted data and also works as a sub-routine for heapsort. STL Functions for Heap Operationsmake_heap(): Converts given range to a heap.push_heap(): Ar
6 min read
What is Max Heap?
Max Heap is a type of binary heap where the key at the root must be the maximum among all keys present in the binary heap. The same property must be recursively true for all nodes in the binary tree. Max Heap Definition:Max Heap is a complete binary tree, where value of each node is greater than or
3 min read
Max Heap meaning in DSA
A max heap is a complete binary tree in which every parent node has a value greater than or equal to its children nodes. Properties of a Max Heap :A max heap is a complete binary tree, meaning that all levels of the tree are completely filled, except possibly the last level which is filled from left
3 min read
std::max in C++
The std::max() is the built-in function in C++ used for finding the maximum among two or more elements passed to it as arguments. It is defined inside <algorithm> header file. In this article, we will learn how to use std::max() function in C++. The std::max() can be used in the following ways
3 min read
max_element in C++ STL
The std::max_element() in C++ is an STL algorithm that is used to find the maximum element in the given range. It is defined inside the <algorithm> header file. In this article, we will learn how to find the maximum element in the range using std::max_element() in C++. Example: [GFGTABS] C++ /
4 min read
(limits.h) in C/C++
The maximum and minimum size of integral values are quite useful or in simple terms, limits of any integral type plays quite a role in programming. Instead of remembering these values, different macros can be used. <climits>(limits.h) defines sizes of integral types. This header defines consta
4 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types. For example, same sorting algorithm can work for different type, so
10 min read
strtoimax() function in C++
The strtoimax() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as an intmax_t(maximum width integer). This function also sets an end pointer that points to the first character after the last valid numeric character of the string,
3 min read
strtoumax() function in C++
The strtoumax() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as an uintmax_t(maximum width unsigned integer). This function also sets an end pointer that points to the first character after the last valid numeric character of th
4 min read
std::min_element in C++
The std::min_element() in C++ is an STL algorithm that is used to find the minimum element in a given range. This range can be array, vector, list or any other container. It is defined inside the <algorithm> header file. In this article, we will learn about the std::min_element() in C++. Examp
4 min read