Repository navigation
Expand file tree
/
Copy pathPriorityQueue.hpp
More file actions
113 lines (101 loc) · 2.77 KB
/
Copy pathPriorityQueue.hpp
File metadata and controls
113 lines (101 loc) · 2.77 KB
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
#ifndef PriorityQueue_hpp
#define PriorityQueue_hpp
#include <iostream>
using namespace std;
// Here we are creating a max heap backed priority queue(array)
// Create a struct data structure with the priority value in the app.Which is the element
template <class T>
class PriorityQueue{
private:
int count; //Number of elements
int capacity; //Maximum number of elements
T *items; // The elements which is stored as an array
void fixUp(int k);
void fixDown(int k);
public:
PriorityQueue(int max);
~PriorityQueue();
bool insert(T ele);
bool getMax(T &ele);
bool peek(T &ele);
int getCount();
T &getItem(int index) { return items[index]; }
void setCount(int newCount) { count = newCount; }
void callFixDown(int k) { fixDown(k); }
//Swap the first element with the last element and then do fixDown on the root node(first element). And return the last element before calling the fixDown.
};
template <class T>
PriorityQueue<T>::PriorityQueue(int max) {
count = 0;
capacity = max;
items = new T[max];
}
template <class T>
PriorityQueue<T>::~PriorityQueue() {
delete[] items;
}
template <class T>
void PriorityQueue<T>::fixUp(int k){ // items is an array which was a heap before the value at k index is inerted.
int ptr = (k-1)/2;
while (k > 0){
if (items[ptr].priority < items[k].priority){
T temp = items[ptr];
items[ptr] = items[k];
items[k] = temp;
k = ptr;
ptr = (k-1)/2;
} else {
break;
}
}
}
template <class T>
void PriorityQueue<T>::fixDown(int p){
int ptr = p;
int ptr1, ptr2;
while (2*p + 1 < count){
ptr1 = (2*p + 1);
ptr2 = (2*p + 2);
if (ptr2 < count && items[ptr2].priority > items[ptr1].priority){
ptr = ptr2;
} else {
ptr = ptr1;
}
if (items[p].priority < items[ptr].priority){
T temp = items[ptr];
items[ptr] = items[p];
items[p] = temp;
p = ptr;
} else {
break;
}
}
}
template <class T>
bool PriorityQueue<T>::insert(T ele) {
if (count == capacity) return false;
items[count] = ele;
fixUp(count);
count++;
return true;
}
template <class T>
bool PriorityQueue<T>::getMax(T &ele) {
if (count == 0) return false;
ele = items[0];
items[0] = items[count - 1];
count --;
fixDown(0);
return true;
}
template <class T>
bool PriorityQueue<T>::peek(T &ele) {
if (count == 0) return false;
ele = items[0];
return true;
}
template <class T>
int PriorityQueue<T>::getCount() {
return count;
}
#endif