Search code examples
carraysheapmin-heap

Implemenation Of A Min Heap Using An Array


I am trying to write a program to represent a min heap using an array. I know that the min heap is similar to a tree data structure where the root node is smaller than it's children. Here is my code:-

# include <stdio.h>
# include <math.h>

int leftChild(int i)
{
    return 2 * i + 1;
}

int rightChild(int i)
{
    return 2 * i + 2;
}

void minHeap(int Arr[], int n, int i)
{
    int l, r, Least;
    l = leftChild(i);
    r = rightChild(i);
    Least = i;

    if(l < n && Arr[l] < Arr[Least])
        Least = l;

    if(r < n && Arr[r] < Arr[Least])
        Least = r;

    if(Least != i)
    {
        int Temp = Arr[i];
        Arr[i] = Arr[Least];
        Arr[Least] = Temp;
        minHeap(Arr, n, Least);
    }
}

int main(void) 
{
    int n;
    printf("\nEnter number of elements : ");
    scanf("%d", &n);

    printf("\nEnter The Elements : ");
    int Arr[n];

    for(int i = 0 ; i < n ; i++)
    {
       scanf("%d", &Arr[i]);
    }

    for(int i = n / 2 - 1 ; i >= 0 ; i--)
      minHeap(Arr, n, i);

    printf("\nMin Heap : ");

    for(int i = 0 ; i < n ; i++)
     printf("%d ", Arr[i]);
    return 0;
}


Input : 
Enter number of elements : 5
Enter the elements : 90 70 10 30 50
Output : 10 30 90 70 50 

But, when I try building the heap on paper, this is the output I get:-

Expected Output : 10 30 70 90 50

Can someone point out the error here for me?


Solution

  • Your program is working correctly. It's your calculation which is at fault.
    A simple visualisation of the steps is as follows.

        90     heapify(Arr,1)
       /  \    swap(1,3)
     >70   10   
     / \
    30  50
    
    
    
       >90     heapify(Arr,0)
       /  \    swap(0,2)
      30   10   
     / \
    70  50
    
    
    
        10   
       /  \   
      30   90   
     / \
    70  50
    

    The resultant minheap should be 10 30 90 70 50