C Program to Implement Max Heap
Last Updated :
24 Apr, 2025
In this article, we will learn the implementation of the max heap in the C programming language.
A heap is a data structure like a tree with some special properties. The basic requirement of the heap is that the value of a node must be greater than equal to (or smaller than equal to) the value of its children and the tree should be a complete binary tree.
What is Max Heap?
The max-heap is the heap where each and every node of a complete binary tree is greater than or equal to its child node. We can see the example of a max-heap in the below image.
Max Heap in C
The above heap can be represented in an array as given below.
arr[] = {17,15,10,6,10,7};
We denote,
- "parent(i)=(i-1)/2" for the parent node.
- "left_child(i)=2*i+1" for the left child.
- "right_child(i)=2*i+2" for the right child.
Here, i is the index of the current node in the array.
For example, To find a parent of the 4th element of the array given below we use parent(4)=(4-1)/2=1th node or element at the index at 1 in an array. We are going to use these three formulas in the implementation of the min heap.
Basic Operations on Min Heap
Following are the basic operations that are performed on the min heap:
- extractMax(): To get the maximum value and remove it from the heap.
- insert(): insert a new item in the heap.
Implementation of the Max Heap in C
To implement the max heap, we will use the structures in C to implement the heap data structure to write the implementation of the max heap to maintain the property of the max heap we have used the bottom-up and top-down approaches both. Let's understand some important functions of the max heap program.
Declaring the Max Heap Structure
Here we have created a structure named Heap where
- arr: Pointer to the dynamic array to store the elements.
- size: Counts the number of elements present in the heap.
- capacity: Indicates how many elements we can insert in a heap.
C
// Declare a heap structure
struct Heap {
int* arr;
int size;
int capacity;
};
// define the struct Heap name
typedef struct Heap heap;
We have used typedef to skip the writing "struct Heap" repeatedly.
Function to Build Max Heap
The createHeap() function is used to create the max heap. Inside this function, we have allocated the memory to the pointer of the heap type using the malloc() function.
Parameters of createHeap()
- capacity: capacity of the max heap.
- nums: pointer to the array of elements.
Return Value of createHeap()
- This function returns the pointer to the allocated min-heap structure with the given elements
C
// Define a createHeap function
heap* createHeap(int capacity, int* nums)
{
// Allocating memory to heap h
heap* h = (heap*)malloc(sizeof(heap));
// Checking if memory is allocated to h or not
if (h == NULL) {
printf("Memory error");
return NULL;
}
// set the values to size and capacity
h->size = 0;
h->capacity = capacity;
// Allocating memory to array
h->arr = (int*)malloc(capacity * sizeof(int));
// Checking if memory is allocated to h or not
if (h->arr == NULL) {
printf("Memory error");
return NULL;
}
int i;
for (i = 0; i < capacity; i++) {
h->arr[i] = nums[i];
}
h->size = i;
i = (h->size - 2) / 2;
while (i >= 0) {
maxHeapify(h, i);
i--;
}
return h;
}
Function to Insert Elements into Max Heap
The insert() function is used for the purpose of inserting the elements in the heap. In this function,
- We first check whether the heap is full or not to avoid an overflow of data.
- If the heap has space, we insert the element into an array and increment the size.
- After inserting the node in a heap we call the insertHelper() function to maintain the min heap as we insert data after the last child node.
Parameters of insert()
- h: pointer to the heap.
- data: data item to be inserted.
Return Value of insert()
- This function does not return anything.
C
// Define a insert function
void insert(heap* h, int data)
{
// Checking if heap is full or not
if (h->size < h->capacity) {
// Inserting data into an array
h->arr[h->size] = data;
// Calling maxHeapify_bottom_up function
insertHelper(h, h->size);
// Incrementing size of array
h->size++;
}
}
Function to Extract the Max Node
This function deletes the root node of the max heap i.e. the maximum value node in the heap.
- First, it is checked if the heap is empty or not.
- If the heap is empty, an error message is printed and the control is returned.
- Otherwise, the root value is stored in the deleteItem variable and replaced with the last item in the heap.
- Then we decrease the size of the heap and call the heapify function at the root node to reorganize the heap.
- At last, the value in deleteItem is returned.
Parameters of extractMin()
Return Value of extractMin()
- Returns the maximum value in the heap.
C
void deleteNode(heap* h)
{
int deleteItem;
// Checking if the heap is empty or not
if (h->size == 0) {
printf("\nHeap id empty.");
return;
}
// Store the node in deleteItem that
// is to be deleted.
deleteItem = h->arr[0];
// Replace the deleted node with the last node
h->arr[0] = h->arr[h->size - 1];
// Decrement the size of heap
h->size--;
// Call maxheapify_top_down for 0th index
// to maintain the heap property
maxheapify(h, 0);
}
Function to Reorganize Heap after Insertion
The insertHelper() is the helper function that is used to reorganize the heap after insertion. This function is called after every insertion of an element in a heap to maintain the property of the max heap. In this function,
- We first check if the element at the root is smaller than its parent.
- If yes, then values are swapped and the function is called recursively for the parent node.
- If not, the control is returned.
Parameters
- h: Pointer to the heap.
- index: Index of the node.
Return Value
C
// Defining maxHeapify_bottom_up function
void insertHelper(heap* h, int index)
{
// Store parent of element at index
// in parent variable
int parent = (index - 1) / 2;
if (h->arr[parent] < h->arr[index]) {
// Swapping when child is smaller
// than parent element
int temp = h->arr[parent];
h->arr[parent] = h->arr[index];
h->arr[index] = temp;
// Recursively calling maxHeapify_bottom_up
insertHelper(h, parent);
}
}
Heapify Function
The maxHeapify() function is the main function in building a heap. In this function,
- We first store the index of a node with the maximum value between the current node, left child, and right child in variable max.
- After that, we check whether the index of a left and right child is within the range that is less than equal to the size of the heap and greater than equal to zero.
- If the min and index are not equal, we swap their value and call maxHeapify() to maintain the max heap.
- Otherwise, we return.
Parameters
- h: Pointer to the heap.
- index: Index of the current node.
Return Value
- Does not return any value.
C
//
void maxHeapify(heap* h, int index)
{
int left = index * 2 + 1;
int right = index * 2 + 2;
int max = index;
// Checking whether our left or child element
// is at right index of not to avoid index error
if (left >= h->size || left < 0)
left = -1;
if (right >= h->size || right < 0)
right = -1;
// store left or right element in max if
// any of these is smaller that its parent
if (left != -1 && h->arr[left] > h->arr[max])
max = left;
if (right != -1 && h->arr[right] > h->arr[max])
max = right;
// Swapping the nodes
if (max != index) {
int temp = h->arr[max];
h->arr[max] = h->arr[index];
h->arr[index] = temp;
// recursively calling for their child elements
// to maintain max heap
maxHeapify(h, max);
}
}
Complete Program of the Max Heap in C
This is the complete code to implement max heap, we have added the main() function and a printHeap() function to print the elements of the heap.
C
#include <malloc.h>
#include <stdio.h>
// Declare a heap structure
struct Heap {
int* arr;
int size;
int capacity;
};
// define the struct Heap name
typedef struct Heap heap;
// forward declarations
heap* createHeap(int capacity, int* nums);
void insertHelper(heap* h, int index);
void maxHeapify(heap* h, int index);
int extractMax(heap* h);
void insert(heap* h, int data);
// Define a createHeap function
heap* createHeap(int capacity, int* nums)
{
// Allocating memory to heap h
heap* h = (heap*)malloc(sizeof(heap));
// Checking if memory is allocated to h or not
if (h == NULL) {
printf("Memory error");
return NULL;
}
// set the values to size and capacity
h->size = 0;
h->capacity = capacity;
// Allocating memory to array
h->arr = (int*)malloc(capacity * sizeof(int));
// Checking if memory is allocated to h or not
if (h->arr == NULL) {
printf("Memory error");
return NULL;
}
int i;
for (i = 0; i < capacity; i++) {
h->arr[i] = nums[i];
}
h->size = i;
i = (h->size - 2) / 2;
while (i >= 0) {
maxHeapify(h, i);
i--;
}
return h;
}
// Defining maxHeapify_bottom_up function
void insertHelper(heap* h, int index)
{
// Store parent of element at index
// in parent variable
int parent = (index - 1) / 2;
if (h->arr[parent] < h->arr[index]) {
// Swapping when child is smaller
// than parent element
int temp = h->arr[parent];
h->arr[parent] = h->arr[index];
h->arr[index] = temp;
// Recursively calling maxHeapify_bottom_up
insertHelper(h, parent);
}
}
void maxHeapify(heap* h, int index)
{
int left = index * 2 + 1;
int right = index * 2 + 2;
int max = index;
// Checking whether our left or child element
// is at right index of not to avoid index error
if (left >= h->size || left < 0)
left = -1;
if (right >= h->size || right < 0)
right = -1;
// store left or right element in max if
// any of these is smaller that its parent
if (left != -1 && h->arr[left] > h->arr[max])
max = left;
if (right != -1 && h->arr[right] > h->arr[max])
max = right;
// Swapping the nodes
if (max != index) {
int temp = h->arr[max];
h->arr[max] = h->arr[index];
h->arr[index] = temp;
// recursively calling for their child elements
// to maintain max heap
maxHeapify(h, max);
}
}
int extractMax(heap* h)
{
int deleteItem;
// Checking if the heap is empty or not
if (h->size == 0) {
printf("\nHeap id empty.");
return -999;
}
// Store the node in deleteItem that
// is to be deleted.
deleteItem = h->arr[0];
// Replace the deleted node with the last node
h->arr[0] = h->arr[h->size - 1];
// Decrement the size of heap
h->size--;
// Call maxheapify_top_down for 0th index
// to maintain the heap property
maxHeapify(h, 0);
return deleteItem;
}
// Define a insert function
void insert(heap* h, int data)
{
// Checking if heap is full or not
if (h->size < h->capacity) {
// Inserting data into an array
h->arr[h->size] = data;
// Calling maxHeapify_bottom_up function
insertHelper(h, h->size);
// Incrementing size of array
h->size++;
}
}
void printHeap(heap* h)
{
for (int i = 0; i < h->size; i++) {
printf("%d ", h->arr[i]);
}
printf("\n");
}
void main()
{
int arr[9] = {1,2,3,4,5,6,7,8,9};
heap* hp = createHeap(9, arr);
printHeap(hp);
extractMax(hp);
printHeap(hp);
}
Output9 8 7 6 5 4 3 2 1
8 6 7 2 5 4 3 1
In the first line of output, we can see elements that are inserted in the heap, and in the second line heap is printed again after deleting one element from the heap.
Â
Similar Reads
C Program to Implement Min Heap
In this article, we will learn the implementation of min heap in C programming language. A heap is a data structure like a tree with some special properties. The basic requirement of the heap is that the value of a node must be greater than equal to (or smaller than equal to) the value of its childr
10 min read
C Program to Implement Queue using Array
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle which means the elements added first in a queue will be removed first from the queue. In this article, we will learn how to implement a Queue using Array in C. Implement Queue using Array in CTo implement Queue u
6 min read
C Program for Heap Sort
Heap sort is a comparison-based sorting technique. It works on the data structure known as "the binary heap". It is one of the most efficient sorting algorithms. It takes relatively less time than selection sort, bubble sort, and insertion sort. Heap sort is an unstable sorting algorithm since the p
4 min read
C Program to Find Largest Element in an Array
In this article, we will learn how to find the largest element in the array using a C program. The simplest method to find the largest element in the array is by iterating the array and comparing each element with the assumed maximum and updating it when the element is greater. [GFGTABS] C #include
3 min read
C Program to Find the Maximum and Minimum Element in the Array
In this article, we will discuss different ways to find the maximum and minimum elements of the array in C. The simplest method to find the maximum and minimum element of the array is iterates through the array and compare each element with the assumed minimum and maximum and update them if the curr
3 min read
How to Release Memory in C?
In C programming, releasing memory means deallocating memory that was previously allocated dynamically using functions like malloc(), calloc(), or realloc(). In this article, we will learn how to release memory in C. Free Dynamic Memory in CTo release the dynamically allocated memory, we can use the
2 min read
C implementation Double-Ended Queue
The double-ended queues, called deques for short, are a generalized form of the queue. It is exactly like a queue except that it does not follow the FIFO rule (First in first out) so, the elements can be added to or removed from either the front(head) or back(tail) of the deque. In this article, we
10 min read
C/C++ Programs
sArray C/C++ Programs C Program to find sum of elements in a given arrayC program to find largest element in an arrayRecursive C program to linearly search an element in a given arrayC program to multiply two matricesC/C++ Program for Given an array A[] and a number x, check for pair in A[] with sum
15+ min read
C program to Find the Largest Number Among Three Numbers
Given 3 integer numbers, the task is to find the largest number among them. Examples Input: a = 10, b = 22, c = 19Output: 22 is the largest number.Explanation: Among the numbers 5, 8, and 3, the largest number is 8.Input: a = 12, b = 7, c = 9Output: 12 is the largest number.Explanation: Among the nu
4 min read
Program to find largest element in an array using Dynamic Memory Allocation
Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation. Examples: Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7. Input: arr[] = {8, 9, 10, 12} Output: 12Explanati
5 min read