Program to implement priority queue using array
PROGRAM
#include<iostream>
using
namespace std;
#define
max 3
struct
item;
{
int p,v;
};
class
pqueue
{
struct item pq[max];
int rear,front;
public:
void insertion();
void deletion();
void display();
pqueue()
{
rear=front=-1;
}
};
void
pqueue::insertion()
{
if(rear==max-1)
cout<<”Priority queue is full”;
else
{
int value,pr,j,i;
cout<<”Enter the value and priority:”;
cin>>value>>pr;
if(front==-1)
{
front=rear=0;
pq[rear].v=value;
pq[rear].p=pr;
}
else
{
for(i=front;i<=rear;i++)
{
if(pq[i].p>pr)
{
for(j=rear;j>=i;j--)
pq[j+1]=pq[j];
}
break;
}
}
pq[i].v=value;
pq[i].p=pr;
rear++;
}
}
}
void
pqueue::deletion()
{
int i,va,pr;
if(front==-1)
cout<<”Priority queue is empty”;
else
{
cout<<”Deleted item
is”<<pq[front].v<<”\t”<<pq[front].p;
for(i=front;i<=rear;i++)
{
pq[i]=pq[i+1];
}
if(front==rear)
front=rear=-1;
else
rear=rear-1;
}
}
void
pqueue::display()
{
if(front==-1)
cout<<”Priority queue is empty”;
else
{
cout<<”Elements of array\n”;
for(int i=front;i<=rear;i++)
cout<<pq[i].v<<”\t”<<pq[i].p<<”\n”;
}
}
int
main()
{
pqueue
p1;
int
c;
char
ch;
do
{
cout<<”Priority queue operations\n”;
cout<<”1.insertion\n”;
cout<<”2.deletion\n”;
cout<<”3.display\n”;
cout<<”Enter your choice:”;
cin>>c;
switch(c)
{
case 1:p1.insertion();
break;
case 2:p1.deletion();
break;
case 3:p1.display();
break;
default:cout<<”Invalid option\n”;
}
cout<<”\nDo you want to continue (y/n):”;
cin>>ch;
}while(ch=='y'||ch=='Y');
return 0;
}
OUTPUT
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:1
Enter
the value and priority:3 4
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:1
Enter
the value and priority:4 1
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:1
Enter
the value and priority:6 2
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:1
Priority
queue is full
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:3
Elements
of array
4
1
6 2
3 4
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:2
Deleted
item is 4 1
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:2
Deleted
item is 6 2
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:2
Deleted
item is 3 4
Do
you want to continue (y/n):y
Priority
queue operations
1.insertion
2.deletion
3.display
Enter
your choice:2
Priority
queue is empty
Do
you want to continue (y/n):n
0 comments:
Post a Comment