#include<stdio.h>
#define N 1000
void build_heap(int *a,int size,int key);
int heap_delete(int *a,int size,int key);
int main()
{
int a[N],b[N],key,choice;
int i,size=0;
int result;
printf("Enter numbers followed by -9999 to stop \n");
for(i=0;;i++)
{
scanf("%d",&key);
if(key==-9999)
{
break;
}
build_heap(a,i,key);
}
size=i;
printf("heaped size %d \n",size);
for(i=1;i<=size;i++)
{
printf("%d ",a[i]);
}
while(1)
{
printf("\nEnter\n1 - ADD \n2 - Delete \n3 - Sort \n0 - Exit\n");
scanf("%d",&choice);
if(choice == 3)
{
printf("sorted \n");
for(i=1;i<=size;i++)
{
b[i]=a[i];
}
for(i=0;i<size;i++)
{
printf("%d ",b[1]);
heap_delete(b,size-i,b[1]);
}
}
else if(choice == 2)
{
printf("Enter the number to be deleted \n");
scanf("%d",&key);
result = heap_delete(a,size,key);
if(result)
size--;
printf("New heap \n");
for(i=1;i<=size;i++)
{
printf("%d ",a[i]);
}
}
else if (choice == 1)
{
printf("Enter the number to be Added \n");
scanf("%d",&key);
build_heap(a,size,key);
size++;
printf("New heap \n");
for(i=1;i<=size;i++)
{
printf("%d ",a[i]);
}
}
else
{
break;
}
}
return 0;
}
void build_heap(int *a,int size,int key)
{
int i,j,temp;
/*Add element to the end*/
a[size+1]=key;
j=size+1;
/*Adjust the heap by moving the new element to right position */
while(j>1 && a[j] > a[j/2])
{
temp = a[j];
a[j] = a[j/2];
a[j/2] = temp;
j=j/2;
}
return;
}
int heap_delete(int *a,int size,int key)
{
int i,j,temp;
/*Return if heap size is zero */
if(size == 0)
return 0;
for(i=1;i<=size;i++)
{
if(key==a[i])
{
/* Replace the deleted element with the
last element in the Heap */
a[i]=a[size];
/*store the element at the end*/
a[size] = key;
break;
}
}
/*Return if Key is not found*/
if(i == size+1)
{
printf(" Key not available \n");
return 0;
}
j=i*2;
/*Adjust the heap*/
while(j < size)
{
/* move to the greater leaf */
if ((j < size-1) && (a[j]<a[j+1]))
j++;
if(a[j/2] < a[j])
{
temp = a[j/2];
a[j/2] = a[j];
a[j] = temp;
j= j*2;
}
else
{
break;
}
}
return 1;
}