Open In App

C Program to Implement Min Heap

Improve
Improve
Like Article
Like
Save
Share
Report

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 children and the tree should be a complete binary tree.

What is Min Heap?

The min-heap is the heap where each and every node of a complete binary tree is less than or equal to its child node. We can see the example of a min-heap in the below image.

min heap in c

Min Heap in C

The above heap can be represented in an array as given below.

arr[] = {6,7,12,10,15,17};

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:

  • extractMin(): To get the minimum value and remove it from the heap.
  • insert(): insert a new item in the heap.

Implementation of Min Heap in C

We will use the structures in C to implement the heap data structure. We will function to build and maintain the min-heap and to provide the basic operations.

Let’s understand the important parts of the min heap program.

Declaring the Min 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 Min Heap

The createHeap() function is used to create the min 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 min heap.

Return Value of createHeap()

  • This function returns the pointer to the allocated heap structure with the given capacity.

The size is initially set to zero.

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) {
        heapify(h, i);
        i--;
    }
    return h;
}


Function to Insert Elements into Min Heap

The insert() function is used for the purpose of inserting the elements in the heap. In this function,

  1. We first check whether the heap is full or not to avoid an overflow of data.
  2. If the heap has space, we insert the element into an array and increment the size.
  3. 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 minHeapify_bottom_up function
        insertHelper(h, h->size);
        // Incrementing size of array
        h->size++;
    }
}


Function to Extract the Min Node

This function deletes the root node of the min heap i.e. the minimum 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()

  • h: Pointer to the heap.

Return Value of extractMin()

  • Returns the minimum value in the heap.

C




// extractMin definition
int extractMin(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 minheapify_top_down for 0th index
    // to maintain the heap property
    minheapify(h, 0);
    return deleteItem;
}


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 min 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

  • No value is returned.

C




// Defining insertHelper 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 insertHelper
        insertHelper(h, parent);
    }
}


Heapify Function

The minHeapify() function is the main function in building a heap. In this function,

  • We first store the index of a node with the minimum value between the current node, left child, and right child in variable min.
  • 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 minHeapify() to maintain the min heap.
  • Otherwise, we return.

Parameters

  • h: Pointer to the heap.
  • index: Index of the current node.

Return Value

  • Does not return any value.

C




// minHeapify() definition
void minHeapify(heap* h, int index)
{
    int left = index * 2 + 1;
    int right = index * 2 + 2;
    int min = index;
 
    // Checking whether our left or child element
    // is at right index or 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 min if
    // any of these is smaller that its parent
    if (left != -1 && h->arr[left] < h->arr[index])
        min = left;
    if (right != -1 && h->arr[right] < h->arr[index])
        min = right;
 
    // Swapping the nodes
    if (min != index) {
        int temp = h->arr[min];
        h->arr[min] = h->arr[index];
        h->arr[index] = temp;
 
        // recursively calling for their child elements
        // to maintain min heap
        minHeapify(h, min);
    }
}


Complete Program of Min Heap in C

This is the complete code to implement min heap, we have added the main() function and a printHeap() function to print the elements of the heap.

C




#include <stdio.h>
#include <stdlib.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 heapify(heap* h, int index);
int extractMin(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) {
        heapify(h, i);
        i--;
    }
    return h;
}
 
// Defining insertHelper 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 insertHelper
        insertHelper(h, parent);
    }
}
 
void heapify(heap* h, int index)
{
    int left = index * 2 + 1;
    int right = index * 2 + 2;
    int min = index;
 
    // Checking whether our left or child element
    // is at right index or 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 min if
    // any of these is smaller that its parent
    if (left != -1 && h->arr[left] < h->arr[index])
        min = left;
    if (right != -1 && h->arr[right] < h->arr[min])
        min = right;
 
    // Swapping the nodes
    if (min != index) {
        int temp = h->arr[min];
        h->arr[min] = h->arr[index];
        h->arr[index] = temp;
 
        // recursively calling for their child elements
        // to maintain min heap
        heapify(h, min);
    }
}
 
int extractMin(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 minheapify_top_down for 0th index
    // to maintain the heap property
    heapify(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 insertHelper 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");
}
 
int main()
{
    int arr[9] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    heap* hp = createHeap(9, arr);
 
    printHeap(hp);
    extractMin(hp);
    printHeap(hp);
 
    return 0;
}


Output

1 2 3 6 5 4 7 8 9 
2 5 3 6 9 4 7 8 

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.

min heap after insertion and deletion

 



Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads