Tuesday, May 17, 2016

WAP to implement Priority Queue

#include<stdio.h>
#include<conio.h>
int pq[15],max=5,r1=-1,f1=-1,r2=4,f2=4,r3=9,f3=9;
void pqins(int x,int p)
{
switch(p)
{
case 1:
if(r1==max-1)
{
printf("Queue is full");
return;
}
r1++;
pq[r1]=x;
if(f1==-1)
f1=0;
break;
case 2:
if(r2==(2*max)-1)
{
printf("Queue is full");
return;
}
r2++;
pq[r2]=x;
if(f2==max-1)
f2=max;
break;
case 3:
if(r3==(3*max)-1)
{
printf("Queue is full");
return;
}
r3++;
pq[r3]=x;
if(f3==(2*max-1))
f3=2*max;
break;
default:
printf("\nEnter priority between 1-3");
}
}
void pqdisplay()
{
int i;
printf("\nPriority Queue 1 element");
for(i=f1;i<=r1 && f1!=-1;i++)
{
printf("\n%d",pq[i]);
}
printf("\nPriority Queue 2 element");
for(i=f2;i<=r2 && f2!=max-1;i++)
{
printf("\n%d",pq[i]);
}
printf("\nPriority Queue 3 element");
for(i=f3;i<=r3 && f3!=(2*max-1);i++)
{
printf("\n%d",pq[i]);
}
}
int pqdel()
{
int x;
if(f1>=0)
{
x=pq[f1];
if(f1==r1)
{
f1=r1=-1;
}
else
{
f1++;
}
}
else if(f2>max-1)
{
x=pq[f2];
if(f2==r2)
{
f2=r2=4;
}
else
{
f2++;
}
}
else if(f3>(2*max-1))
{
x=pq[f3];
if(f3==r3)
{
f3=r3=9;
}
else
{
f3++;
}
}
else
{
printf("No elements in queue");
}
return x;
}
void main()
{
int n,x,p;
clrscr();
do
{
printf("\n1.Insert ");
printf("\n2.delete ");
printf("\n3.display ");
printf("\n4.exit");
printf("\nEnter your choice :");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nEnter value :");
scanf("%d",&x);
printf("\nEnter priority :");
scanf("%d",&p);
pqins(x,p);
break;
case 2:
x=pqdel();
printf("\n Deleted value is %d",x);
break;
case 3:
pqdisplay();
break;
case 4:
printf("\nThank you");
break;
default:
printf("\nInvalid choice");
}

}while(n!=4);
getch();
}

No comments:

Post a Comment