Priority Queue
Priority Queue
AIM:
To implement a priority queue using an array.
ALGORITHM:
STEP 1: Define a structure called heap,with data members-
capacity,size,elements.
CODE:
#include<stdio.h>
struct heap;
typedef struct heap *pq;
struct heap
{
int capacity;
int size;
int *elements;
};
pq h;
pq initial(int max)
{
/*if(max<minheap)
printf("\n heap size is too small");*/
h=malloc(sizeof(struct heap));
if(h==NULL)
printf("\n out of space");
h->elements=malloc((max+1)*sizeof(int));
if(h->elements==NULL)
printf("\n out of space\n");
h->capacity=max;
h->size=0;
h->elements[0]=-100;
return h;
}
int isfull(pq h)
{
return h->size==h->capacity;
}
int isempty(pq h)
{
return h->size==0;
}
void insert(int x,pq h)
{
int i;
if(isfull(h))
{
printf("priority queue is full");
return;
}
for(i=++h->size;h->elements[i/2]>x;i/=2)
h->elements[i]=h->elements[i/2];
h->elements[i]=x;
}
int deletemin(pq h)
{
int i,child;
int minelement,lastelement;
if(isempty(h))
{
printf("\n priority queue is full");
return h->elements[0];
}
minelement=h->elements[1];
lastelement=h->elements[h->size--];
for(i=1;i*2<=h->size;i=child)
{
child=2*i;
if(child!=h->size&&h->elements[child+1]<h->elements[child])
child++;
if(lastelement>h->elements[child])
h->elements[i]=h->elements[child];
else
break;
}
h->elements[i]=lastelement;
return minelement;
}
void find(int x,pq h)
{
int i;
for(i=1;i<=h->size;i++)
{
if(h->elements[i]==x)
{
printf("\nelement found in position %d",i);
return;
}
}
printf("\nelement not found in the heap");
}
void display(pq h)
{
int i;
printf("\n THE PRIORITY QUEUE IS:");
for(i=1;i<=h->size;i++)
printf("\n %d",h->elements[i]);
}
main()
{
int ch,n,x;
pq h;
printf("\n enter the no of elements:");
scanf("%d",&n);
h=initial(n);
while(1)
{
printf("\n enter your choice:");
printf("\n1.insert\n2.deletemin\n3.find\n4.display\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n enter the number to be inserted");
scanf("%d",&x);
insert(x,h);
display(h);
break;
case 2:
printf("\n the minimum element is:");
deletemin(h);
display(h);
break;
case 3:
printf("\n enter the element to be searched:");
scanf("%d",&x);
find(x,h);
break;
case 4:
display(h);
break;
default:
exit(0);
}
}
}
OUTPUT:
1.Insert
2.Deletemin
3.Find
4.Exit Enter ur choice:2
RESULT:
Thus the program to implement priority queue is done successfully and
executed.