-
Notifications
You must be signed in to change notification settings - Fork 2
/
Priority Queue.cpp
102 lines (99 loc) · 2.06 KB
/
Priority Queue.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
#include <bits/stdc++.h>
using namespace std;
#define max_size 100
class priorityQueue
{
int queueSize, q[max_size];
int left(int index);
int right(int index);
int parent(int index);
void maxHeapify(int index);
public:
void insert(int item);
int maximumItem();
int extractMax();
void increaseKey(int item, int pos);
};
int priorityQueue :: left(int index)
{
return 2 * index + 1;
}
int priorityQueue :: right(int index)
{
return 2 * index + 2;
}
int priorityQueue :: parent(int index)
{
return (index - 1) / 2;
}
void priorityQueue :: maxHeapify(int index)
{
int l = left(index), r = right(index), greatest = index;
if(l < queueSize)
{
if(l < queueSize && q[l] > q[greatest])
greatest = l;
if(r < queueSize && q[r] > q[greatest])
greatest = r;
}
if(greatest != index)
{
int temp = q[index];
q[index] = q[greatest];
q[greatest] = temp;
maxHeapify(greatest);
}
}
void priorityQueue :: insert(int item)
{
q[queueSize] = INT_MIN;
increaseKey(queueSize++, item);
queueSize++;
}
int priorityQueue :: maximumItem()
{
if(queueSize <= 0)
{
cout<<"Empty Queue\n";
return -1;
}
return q[0];
}
void priorityQueue :: increaseKey(int index, int newKey)
{
if(queueSize <= 0)
{
cout<<"Empty Queue\n";
return;
}
if(newKey < q[index])
{
cout<<"New Value smaller than earlier\n";
return;
}
q[index] = newKey;
while(index > 0 && q[parent(index)] < q[index])
{
int temp = q[index];
q[index] = q[parent(index)];
q[parent(index)] = temp;
index = parent(index);
}
}
int priorityQueue :: extractMax()
{
if(queueSize <= 0)
{
cout<<"Empty Queue\n";
return -1;
}
int temp = q[0];
q[0] = q[queueSize - 1];
q[queueSize - 1] = temp;
queueSize--;
maxHeapify(0);
}
int main()
{
return 0;
}