-
Notifications
You must be signed in to change notification settings - Fork 33
/
priorityQueue.cpp
171 lines (157 loc) · 4.15 KB
/
priorityQueue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
struct data
{
char job[10];
int prno , ord;
};
const int MAX=5;
class priority_queue
{
private:
data d[MAX];
int front,rear;
public:
priority_queue()
{
front=rear=-1;
for(int i=0;i<MAX;i++)
{
strcpy(d[i].job,"\0");
d[i].prno=d[i].ord=0;
}
}
void add(data dt)
{
if(rear==MAX-1)
{
cout<<"Queue is full";
}
else
{
rear++;
d[rear]=dt;
if(front==-1)
{ front=0; }
}
}
void remove()
{
int highestPriority = 0;
int ind = -1;
data temp;
for(int i=front;i<=rear;i++)
{
if (highestPriority == d[i].prno && ind > -1 && d[ind].job < d[i].job)
{
highestPriority = d[i].prno;
ind = i;
}
else if (highestPriority < d[i].prno)
{
highestPriority = d[i].prno;
ind = i;
}
}
if(front==-1)
{
cout<<"Queue is empty";
}
else
{
for(int i=ind;i<rear;i++)
{
d[i] = d[i + 1];
}
}
rear--;
}
void sort()
{
data temp;
for(int i=front;i<rear;i++)
{
for(int j=i+1; j<=rear;j++)
{
if(d[i].prno>d[j].prno)
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
else if(d[i].prno==d[j].prno)
{
if(d[i].ord>d[j].ord)
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}
}
}
display();
}
void display()
{
if(front==-1)
{
cout<<"Queue is empty";
}
else
{
for(int i=front;i<=rear;i++)
{
cout<<d[i].job<<" ";
}
}
cout<<endl;
}
};
int main ()
{
priority_queue p;
int ord=0;
while(true)
{
cout<< "Priority Queue Operations :- "<<endl;
cout<< "1 -> ADD"<<endl;//add element at end
cout<< "2 -> REMOVE "<<endl; //removes element from front
cout<< "3 -> DISPLAY"<<endl;//display all the elements
cout<< "4 -> SORT BY PRIORITY "<<endl;
cout<< "5 -> EXIT"<<endl;
int c;
cout<<"Enter your choice :";
cin >>c;
switch(c)
{
case 1:
data d;
cout<<"Enter the data : ";
cin >>d.job;
cout<<"Enter the Priority no : ";
cin >>d.prno;
d.ord=ord++;
p.add(d);
break;
case 2:
p.remove();
break;
case 3:
p.display();
break;
case 4:
p.sort();
break;
case 5:
exit(0);
default:
cout<<"Invalid Input"<<endl;
false;
break;
}
}
return 0 ;
}