-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.hpp
More file actions
104 lines (80 loc) · 1.86 KB
/
PriorityQueue.hpp
File metadata and controls
104 lines (80 loc) · 1.86 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
#ifndef PRIORITYQUEUE_H
#define PRIORITYQUEUE_H
#include<iostream>
#include<stdexcept>
template <class T>
class PriorityQueue{
private:
T *items;
int capacity;
int n;
void fixUp(int k);
void fixDown(int k);
public:
PriorityQueue(int capacity);
bool insert(T elt);
bool getmax(T &elt);
bool isEmpty();
int size();
~PriorityQueue();
};
template<class T>
PriorityQueue<T>::PriorityQueue(int capacity){
this -> capacity = capacity;
items = new T[capacity];
n = 0;
};
template <class T>
bool PriorityQueue<T> ::insert(T elt){
if (n >= capacity) return false;
items[n++] = elt;
fixUp(n);
return true;
};
template <class T>
bool PriorityQueue<T> ::getmax(T& elt){
if (isEmpty()) return false;
elt = items[0];
std::swap(items[0], items[n - 1]);
n--;
fixDown(0);
return true;
};
template <class T>
void PriorityQueue<T> ::fixUp(int index){
T value = items[index];
while(index > 0){
int parent = (index - 1)/ 2;
if (value <= items[parent]) break;
items[index] = items[parent];
index = parent;
}
items[index] = value;
};
template <class T>
void PriorityQueue<T> ::fixDown(int index){
T value = items[index];
while(2 * index + 1 < n){
int child = 2 * index + 1;
if (child < n && items[child + 1] > items[child]){
child ++;
}
if (value >= items[child]) break;
items[index] = items[child];
index = child;
}
items[index] = value;
};
template <class T>
bool PriorityQueue<T> ::isEmpty(){
return n == 0;
};
template <class T>
int PriorityQueue<T>:: size(){
return n;
}
template <class T>
PriorityQueue<T>::~PriorityQueue(){
delete [] items;
}
#endif