Skip to main content

Min Heap Implementation

Min heap is an almost complete binary tree in which root element's value is lesser than all children and the same rule applies for all other nodes as well.

// A C++ program to showcase the common min heap operations

#include <iostream>
using namespace std;

void swapValues(int *a, int *b){
    int t = *a;
    *a = *b;
    *b = t;
}

// A class for minHeap
class MinHeap{
    int *harr; // pointer to array of elements in min heap
    int capacity; //maximum capacity of heap
    int current_size; // count of elements currently present  in heap
    public:
        MinHeap(int capacity); // constructor
        int getMin(); // minimum element of the heap
        int extractMin(); // extract minimum element from the heap
        int left(int i); // index of left child of the element present at index i
        int right(int i); // index of right child of the element present at index i
        int parent(int i); // index of the parent of the element present at index i
        void minHeapify(int i); // helper function to maintain the minHeap property of min heap
        void insertKey(int k); // insert a value k in heap
        void deleteKey(int i); // delete key present at index i
        void decreaseKey(int i, int new_val); //decrease value at index i with new_val
};

MinHeap::MinHeap(int cap){
    current_size = 0;
    capacity = cap;
    harr = new int[capacity];
}

int MinHeap::left(int i){
    return (2*i +1);
}

int MinHeap::right(int i){
    return (2*i+2);
}

int MinHeap::parent(int i){
    if(i<=0) return -1;
    return (i-1)/2;
}

int MinHeap::getMin(){
    return harr[0];
}

void MinHeap::minHeapify(int i){
    int l = left(i);
    int r = right(i);
    int smallest = i;
    if(l < current_size && harr[l] < harr[smallest])
        smallest = l;
    if(r < current_size && harr[r] < harr[smallest])
        smallest = r;
    if(smallest != i){
        swapValues(&harr[i], &harr[smallest]);
        minHeapify(smallest);
    }
}

void MinHeap:: decreaseKey(int i, int new_val){
    if(new_val > harr[i])
        return;
    harr[i] = new_val;
    while(i!=0 && harr[parent(i)] > harr[i]){
       swapValues(&harr[parent(i)], &harr[i]);
       i = parent(i);
    }
}

int MinHeap:: extractMin(){
    if(current_size <= 0)
        return INT_MAX;
    if(current_size == 1){
        current_size--;
        return harr[0];
    }
    int min_val = harr[0];
    harr[0] = harr[current_size-1];
    current_size--;
    minHeapify(0);
    return min_val;
}

void MinHeap:: deleteKey(int i){
    decreaseKey(i, INT_MIN);
    extractMin();
}

void MinHeap:: insertKey(int k){
    if(current_size == capacity){
        cout<<"Heap Overflow"<<endl;
        return;
    }
    // insert your val at the last
    harr[current_size] = k;
    int i = current_size;
    current_size++;
   // to maintain the min heap property
    while(i!=0 && harr[parent(i)] > harr[i]){
        swapValues(&harr[parent(i)], &harr[i]);
        i = parent(i);
    }
}

int main()
{
    MinHeap h(20);
    h.insertKey(3);
    h.insertKey(2);
    h.deleteKey(1);
    h.insertKey(15);
    h.insertKey(5);
    h.insertKey(4);
    h.insertKey(45);
    cout << h.extractMin() << " ";
    cout << h.getMin() << " ";
    h.decreaseKey(2, 1);
    cout << h.getMin();
    return 0;
}

Comments

Popular Articles

Rotate the Matrix: You are given a NxN matrix.You have to rotate same coloured rectangle clockwise or anticlockwise alternatively by a ‘k’ value. K value keeps on increasing by one as we move from outer to inner loop.Suppose in the given figure outermost loop is rotated by 1 place clockwise followed by next loop rotated by 2 places anticlockwise and so on. [Give only Inplace solution]. // Picture taken from :  https://www.geeksforgeeks.org/factset-interview-experience-set-12-campus/ Solution: #include <iostream> using namespace std; #define N 5 void printMatrix (int A[][N]){     for(int i=0; i<N; i++){         for(int j=0; j<N; j++)             cout<<A[i][j]<<' ';         cout<<endl;     }     } void rotateMatrix (int A[][N]){     int l = 0, r = N-1, t = 0, b = N-1;     int k = 1; ...

Snake and Fruit Game

A Snake and fruit game in C++ using basic data structures and algorithm. In this game initially there is a fruit at some random location and snake head lies in the middle of the console. By pressing left, right, top, down buttons, snake head moves accordingly. If stop button is pressed, game is paused.  If the snake eats the fruit then its tail’s length increase, score increases by ten points and a new fruit is generated at some random location in the console. If snake hits the wall or bites itself then the game will terminate. This game was developed in C/C++ using code-blocks IDE. Code :  //  header files #include <bits\stdc++.h> #include<conio.h> #include<windows.h> using namespace std; bool gameOver; // to check whether game is over or not const int width = 30;   // width of the window const int height = 20;  // height of the window int x; // current x-position of the snake int y; //  current y-pos...