forked from ccgcv/Cplus-plus-for-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Priority Queue In CPP
110 lines (90 loc) · 1.94 KB
/
Priority Queue In 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
// C++ program to implement Priority Queue
// using Arrays
#include <bits/stdc++.h>
using namespace std;
// Structure for the elements in the
// priority queue
struct item {
int value;
int priority;
};
// Store the element of a priority queue
item pr[100000];
// Pointer to the last index
int size = -1;
// Function to insert a new element
// into priority queue
void enqueue(int value, int priority)
{
// Increase the size
size++;
// Insert the element
pr[size].value = value;
pr[size].priority = priority;
}
// Function to check the top element
int peek()
{
int highestPriority = INT_MIN;
int ind = -1;
// Check for the element with
// highest priority
for (int i = 0; i <= size; i++) {
// If priority is same choose
// the element with the
// highest value
if (highestPriority == pr[i].priority && ind > -1
&& pr[ind].value < pr[i].value) {
highestPriority = pr[i].priority;
ind = i;
}
else if (highestPriority < pr[i].priority) {
highestPriority = pr[i].priority;
ind = i;
}
}
// Return position of the element
return ind;
}
// Function to remove the element with
// the highest priority
void dequeue()
{
// Find the position of the element
// with highest priority
int ind = peek();
// Shift the element one index before
// from the position of the element
// with highest priority is found
for (int i = ind; i < size; i++) {
pr[i] = pr[i + 1];
}
// Decrease the size of the
// priority queue by one
size--;
}
// Driver Code
int main()
{
// Function Call to insert elements
// as per the priority
enqueue(10, 2);
enqueue(14, 4);
enqueue(16, 4);
enqueue(12, 3);
// Stores the top element
// at the moment
int ind = peek();
cout << pr[ind].value << endl;
// Dequeue the top element
dequeue();
// Check the top element
ind = peek();
cout << pr[ind].value << endl;
// Dequeue the top element
dequeue();
// Check the top element
ind = peek();
cout << pr[ind].value << endl;
return 0;
}