## Pages

### HEAP Algorithm in C program Data Structure

This Program is for HEAP in C, and is a part of Mumbai University MCA Colleges Data Structure MCA Sem 2

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

void insert(int num,int n);
void del(int num);
void dis();

int n,arr[100];

void main()
{
int choice,num;
n=0;
clrscr();
printf("\n================= HEAP ========================\n");
while(1)
{
printf("1.INSERT\n\n");
printf("2.DELETE\n\n");
printf("3.DISPLAY\n\n");
printf("4.EXIT\n\n");
scanf("%d",&choice);

switch(choice)
{
case 1:
printf("\n~~~~~~~~~~~~~ INSERTING ~~~~~~~~~~~~~~");
printf("\n\nEnter the number to be inserted:");
scanf("%d",&num);
insert(num,n);
n=n+1;
break;

case 2:
printf("\n~~~~~~~~~~~~~ DELETING ~~~~~~~~~~~~~~");
printf("\n\nEnter the number to be deleted:");
scanf("%d",&num);
del(num);
break;

case 3:
printf("\n~~~~~~~~~~~~~ DISPLAYING ~~~~~~~~~~~~~~\n");
dis();
break;

case 4:
exit();

default:
printf("\nINVALID ENTRY !!! TRY AGAIN\n");

}
}
}

void dis()
{
int i;
if(n==0)
{
printf("\n\n------------------------------\n\n");
printf("HEAP IS EMPTY");
printf("\n\n------------------------------\n\n");
return;
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\t",arr[i]);
printf("\n");

}

void insert (int num,int loc)
{
int par;
while(loc>0)
{
par=(loc-1)/2;
if(num<=arr[par])
{
arr[loc]=num;
return;
}
arr[loc]=arr[par];
loc=par;
}
arr[0]=num;
}

void del(int num)
{
int left,right,i,temp,par;
for(i=0;i<n;i++)
{
if(num==arr[i])
break;
}
if(num!=arr[i])
{
printf("\n\n------------------------------\n\n");
printf("\n\n------------------------------\n\n");
return;
}
arr[i]=arr[n-1];
n=n-1;
par=(i-1)/2;

if(arr[i]>arr[par])
{
insert(arr[i],i);
return;
}

left=2*i+1;
right=2*i+2;

while(right<n)
{
if(arr[i]>=arr[left] && arr[i]>=arr[right])
return;
if(arr[right]<=arr[left])
{
temp=arr[i];
arr[i]=arr[left];
arr[left]=temp;
i=left;
}
else
{
temp=arr[i];
arr[i]=arr[right];
arr[right]=temp;
i=right;
}
left=2*i+1;
right=2*i+2;
}
if(left==n-1 && arr[i]<arr[left])
{
temp=arr[i];
arr[i]=arr[left];
arr[left]=temp;
}

}

Hope this Program is useful to you in some sense or other. Keep on following this blog for more Mumbai University MCA College Programs. Happy Programming and Studying.