Program - Priority Queue
// Priority queue
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 5
// Structure for data
struct data
{
int val,p,o;
}d[MAX];
int front=-1,rear=-1;
// Insert operation
void insert(struct data d1)
{
struct data temp;
int i,j;
if(rear==MAX-1)
{
printf("\n Priority Queue is Full...");
getch();
}
else
{
rear++;
d[rear]=d1;
if(front==-1)
front=0;
for(i=front;i<=rear;i++) // arrange priority
{
for(j=i+1;j<=rear;j++)
{
if(d[i].p > d[j].p)
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
else
{
if(d[i].p==d[j].p) // if two job has same priority
{
if(d[i].o > d[j].o) // arrange as per order from
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}
}
}
}
}
}
// Delete operation
void deletion()
{
struct data d1;
if(front==-1)
printf("\n Priority Queue is Empty...");
else
{
printf("-------------------------------\n");
printf("\n Value: %d",d[front].val);
printf("\n Priority: %d",d[front].p);
printf("\n Order: %d",d[front].o);
printf("\n -------------------------------");
if(front==rear)
front=rear=-1;
else
front++;
}
}
// Display operation
void display()
{
int i;
if(front==-1)
printf("\n Priority Queue is Empty...");
else
{
for(i=front;i<=rear;i++)
{
printf("\n -------------------------------");
printf("\n Object : %d",i+1);;
printf("\n Value : %d",d[i].val);
printf("\n Priority: %d",d[i].p);
printf("\n Order : %d",d[i].o);
printf("\n -------------------------------");
}
}
}
// main() section
void main()
{
struct data d1;
// Executable section
do
{
int ch;
clrscr();
// Print menu
printf("\n-------------------");
printf("\n M E N U ");
printf("\n-------------------");
printf("\n1 Insertion");
printf("\n2 Deletion");
printf("\n3 Display");
printf("\n4 Exit");
printf("\n-------------------");
printf("\nEnter Choice... ");
scanf("%d",&ch);
switch(ch)
{
// Insertion case
case 1:
printf("\n\t\tEnter Value:- ");
scanf("%d",&d1.val);
printf("\n\t\tEnter Priority:- ");
scanf("%d",&d1.p);
printf("\n\t\tEnter Order:- ");
scanf("%d",&d1.o);
insert(d1);
break;
// Deletion case
case 2:
deletion();
getch();
break;
// Display case
case 3:
display();
getch();
break;
// Exit case
case 4:
exit(0);
// Default case
default:
printf("\nInvalid Choice...");
getch();
}
}while(1);
getch();
}
Posted By : Ruchita Pandya