Open In App

C Program to Implement Min Heap

Last Updated : 27 Oct, 2025
Comments
Improve
Suggest changes
8 Likes
Like
Report

Min-Heap is a Data Structure with the following properties.

  • It is a complete Complete Binary Tree.
  • The value of the root node must be the smallest among all its descendant nodes and the same thing must be done for its left and right sub-tree also.


Internal Implementation of Min-Heap Data Structure

A heap can be efficiently represented using an array.

  • If a node is stored at index i:
  • Its left child is at index 2*i + 1.
  • Its right child is at index 2*i + 2.
  • The parent of a node at index i can be found at index [(i-1)/2].

Operations on Min-heap

Here are some common operations that can be performed on a Heap Data Structure

Insertion - O(log n) Time and O(n) Space

The insertion operation in a min-heap involves the following steps:

  • Add the new element to the end of the heap, in the next available position in the last level of the tree.
  • Compare the new element with its parent. If the parent is greater than the new element, swap them.
  • Repeat step 2 until the parent is smaller than or equal to the new element, or until the new element reaches the root of the tree.
insertion-in-Minimum-heap
C++
#include <stdio.h>

#define MAX 100

int heap[MAX];
int size = 0;

// Swap two integers
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Insert into Min Heap
void insert(int value)
{
    heap[size] = value;
    int index = size;
    size++;

    // Heapify up
    while (index > 0 && heap[(index - 1) / 2] > heap[index])
    {
        swap(&heap[index], &heap[(index - 1) / 2]);
        index = (index - 1) / 2;
    }
}

// Display heap
void display()
{
    for (int i = 0; i < size; i++)
        printf("%d ", heap[i]);
    printf("\n");
}

int main()
{
    int values[] = {10, 3, 2, 4, 5, 1};
    int n = sizeof(values) / sizeof(values[0]);

    for (int i = 0; i < n; i++)
    {
        insert(values[i]);
        printf("Inserted %d into the min-heap: ", values[i]);
        display();
    }

    return 0;
}

Output
Inserted 10 into the min-heap: 10 
Inserted 3 into the min-heap: 3 10 
Inserted 2 into the min-heap: 2 10 3 
Inserted 4 into the min-heap: 2 4 3 10 
Inserted 5 into the min-heap: 2 4 3 10 5 
Inserted ...

Deletion -O(long n) Time and O(n) Space

Removing the smallest element (the root) from a Min-Heap involves the following steps:

  • Replace the root (or the element to be deleted) with the last element in the heap.
  • Remove the last element from the heap, since it has been moved to the root.
  • Heapify-down: The element now at the root may violate the Min-Heap property, so perform heapify starting from the root to restore the heap property.


C
#include <stdio.h>

#define MAX 100

int heap[MAX];
int size = 0;

// Swap two integers
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Insert into Min Heap
void insert(int value)
{
    heap[size] = value;
    int index = size;
    size++;

    // Heapify up
    while (index > 0 && heap[(index - 1) / 2] > heap[index])
    {
        swap(&heap[index], &heap[(index - 1) / 2]);
        index = (index - 1) / 2;
    }
}

// Delete a value from Min Heap
void deleteMin(int value)
{
    int index = -1;

    // Find index of the value to delete
    for (int i = 0; i < size; i++)
    {
        if (heap[i] == value)
        {
            index = i;
            break;
        }
    }
    if (index == -1)
        return; // Value not found

    // Replace with last element
    heap[index] = heap[size - 1];
    size--;

    // Heapify down
    while (1)
    {
        int left = 2 * index + 1;
        int right = 2 * index + 2;
        int smallest = index;

        if (left < size && heap[left] < heap[smallest])
            smallest = left;
        if (right < size && heap[right] < heap[smallest])
            smallest = right;

        if (smallest != index)
        {
            swap(&heap[index], &heap[smallest]);
            index = smallest;
        }
        else
        {
            break;
        }
    }
}

// Display heap
void display()
{
    for (int i = 0; i < size; i++)
        printf("%d ", heap[i]);
    printf("\n");
}

int main()
{
    int values[] = {13, 16, 31, 41, 51, 100};
    int n = sizeof(values) / sizeof(values[0]);

    // Insert elements
    for (int i = 0; i < n; i++)
        insert(values[i]);

    printf("Initial heap: ");
    display();

    // Delete element 13
    deleteMin(13);
    printf("Heap after deleting 13: ");
    display();

    return 0;
}

Output
Initial heap: 13 16 31 41 51 100 
Heap after deleting 13: 16 41 31 100 51 

Peek operation - O(1) Time and O(n) Space

 To access the minimum element (i.e., the root of the heap), the value of the root node is returned.

n8
C
#include <stdio.h>

#define MAX 100

int heap[MAX];
int size = 0;

// Swap two integers
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Function to insert an element into min-heap
void insert(int value)
{
    // Add the new element at the end
    heap[size] = value;
    int index = size;
    size++;

    // Heapify-up to maintain min-heap property
    while (index > 0 && heap[(index - 1) / 2] > heap[index])
    {
        swap(&heap[index], &heap[(index - 1) / 2]);
        index = (index - 1) / 2;
    }
}

// Function to get the peak element of min-heap
int top()
{
    if (size > 0)
        return heap[0]; // Root element
    return -1;          // Heap is empty
}

int main()
{
    // Insert elements into the min-heap
    insert(51);
    insert(41);
    insert(31);
    insert(16);
    insert(13);

    // Get the peak element (smallest in min-heap)
    int peakElement = top();
    printf("Peak element: %d\n", peakElement);

    return 0;
}

Output
Peak element: 13

Implementation of Min- Heap


Output
Min Heap: 3 5 20 10 
Extracted Min: 3
Heap after extraction: 5 10 20 

Heapify -O(n) Time and O(n) Space

The heapify operation is used to place an element in its correct position within the heap so that the heap property is maintained.
A heapify operation can also be used to create a min heap from an unsorted array. This is done by starting at the last non-leaf node and repeatedly performing the "heapify down" operation until all nodes satisfy the heap property. 

Heapify-Operation-in-min-heap
C
#include <stdio.h>

#define MAX 100

// Swap two integers
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Heapify function for min-heap
void heapify(int arr[], int i, int n)
{
    int smallest = i;
    int l = 2 * i + 1;
    int r = 2 * i + 2;

    // If left child exists and is smaller than root
    if (l < n && arr[l] < arr[smallest])
        smallest = l;

    // If right child exists and is smaller than smallest so far
    if (r < n && arr[r] < arr[smallest])
        smallest = r;

    // If smallest is not root, swap and continue heapifying
    if (smallest != i)
    {
        swap(&arr[i], &arr[smallest]);
        heapify(arr, smallest, n);
    }
}

int main()
{
    int arr[] = {2, 3, 10, 4, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    // Build min-heap: heapify from last non-leaf node up to root
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, i, n);

    // Print array after min-heapify
    printf("\nMin-Heap after heapify operation: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

Output
Original array: 2 3 10 4 5 1 
Min-Heap after heapify operation: 1 3 2 4 5 10 

Applications of Min-Heap Data Structure

  • Heap Sort: Min-heap is used to implement heap sort, an efficient O(nlog⁡n) sorting algorithm.
  • Priority Queue: Min-heap ensures the smallest element is always at the root, enabling efficient priority queue operations.
  • Dijkstra’s Algorithm: Min-heap stores vertices by minimum distance for efficient shortest-path computation.
  • Huffman Coding: Min-heap implements a priority queue to build optimal prefix codes.
  • Merge K Sorted Arrays: Min-heap efficiently merges K sorted arrays into one sorted array.

Advantages of Min-heap Data Structure

  • Fast Insertion and Deletion: Supports insertion and removal in O(log⁡n) time, maintaining heap property efficiently.
  • Quick Access to Minimum: The smallest element is always at the root, retrievable in O(1) time.
  • Compact Storage: Can be implemented using arrays, saving memory compared to pointer-based structures.

Article Tags :

Explore