-
Notifications
You must be signed in to change notification settings - Fork 0
/
IndexedPriorityQueue.java
294 lines (252 loc) · 6.85 KB
/
IndexedPriorityQueue.java
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package dsa_dp.data_structures.queue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class IndexedPriorityQueue<K, V extends Comparable<V>> {
private static final int DEFAULT_MAX_SIZE = 20;
private final int[] pm, im;
private final int maxSize;
private final HashMap<K, Integer> map;
private final ArrayList<V> values;
private int size = 0;
/**
* Default constructor
*/
public IndexedPriorityQueue() {
this(DEFAULT_MAX_SIZE);
}
/**
* Constructor with given size
*
* @param maxSize int
*/
public IndexedPriorityQueue(int maxSize) {
this.maxSize = maxSize;
values = new ArrayList<>(maxSize);
map = new HashMap<>(maxSize);
pm = new int[maxSize];
im = new int[maxSize];
prePopulateArrays();
}
/**
* Inserts a new element in the IPQ (Duplicates are NOT allowed)
*
* @param key K
* @param value V
* @return boolean
*/
public boolean insert(K key, V value) {
if (map.containsKey(key) || size > maxSize)
return false;
// Populating the internal arrays
map.put(key, size);
values.set(size, value);
pm[size] = size;
im[size] = size;
swim(size);
size++;
return true;
}
/**
* Removes and returns the first element's key of the Priority Queue
*
* @return T
*/
public K poll() {
return remove(getMapKey(im[0]));
}
/**
* @param key K
* @return K
*/
public K remove(K key) {
if (map.containsKey(key)) {
int keyPos = pm[map.get(key)];
swap(keyPos, size - 1);
values.set(im[size - 1], null);
pm[im[size - 1]] = -1;
im[size - 1] = -1;
map.remove(key);
sink(keyPos);
swim(keyPos);
size--;
return key;
}
return null;
}
/**
* Updates the value corresponding to the given key and returns true,
* false if the update did not succeed
*
* @param key K
* @param val V
* @return boolean
*/
public boolean update(K key, V val) {
if (val == null)
return false;
int ki = map.get(key);
values.set(ki, val);
sink(pm[ki]);
swim(pm[ki]);
return true;
}
/**
* Whether the IndexedPriorityQueue already contains the given key or not
*
* @param key the key to search
* @return whether it contains the given key or not
*/
public boolean contains(K key) {
return map.containsKey(key);
}
/**
* Prints the data structure in a debugging friendly format
*/
public void print() {
System.out.println("VAL: " + values);
System.out.println("PM: " + Arrays.toString(pm));
System.out.println("IM: " + Arrays.toString(im));
System.out.print("LVL ORDER: [ ");
for (int i = 0; i < size; i++) {
try {
System.out.print(values.get(im[i]) + " ");
} catch (Exception e) {
System.out.print("null ");
}
}
System.out.println("]");
}
/**
* Returns the current elements number inside the priority queue
*
* @return int
*/
public int size() {
return this.size;
}
/**
* Returns the previously set max size of this priority queue
*
* @return int
*/
public int getMaxSize() {
return this.maxSize;
}
/**
* Moves 'up' the given node until it satisfy the MIN Heap invariant
* If the given value is lower than the parent let's swap
*
* @param i int
*/
private void swim(int i) {
int p = (i - 1) / 2;
if (size < 0 || im[i] == -1 || im[p] == -1)
return;
while (values.get(im[i]).compareTo(values.get(im[p])) < 0) {
swap(i, p);
i = p;
p = (i - 1) / 2;
}
}
/**
* Moves 'down' the given node until it satisfy the MIN Heap invariant
* If the given value is greater than one of its children let's swap with the child having the lower value
*
* @param i int
*/
private void sink(int i) {
int lowerI = getLowerValueChildIndex(i);
if (lowerI == -1) return; // No children scenario
while (values.get(im[i]).compareTo(values.get(im[lowerI])) > 0) {
swap(i, lowerI);
i = lowerI;
lowerI = getLowerValueChildIndex(i);
if (lowerI == -1) break;
}
}
/**
* Swaps indexes accordingly in the position map and inverse map
*
* @param i int
* @param p int
*/
private void swap(int i, int p) {
pm[im[p]] = i;
pm[im[i]] = p;
int temp = im[i];
im[i] = im[p];
im[p] = temp;
}
/**
* Populates the instance array attributes with placeholder/default values
*/
private void prePopulateArrays() {
for (int i = 0; i < maxSize; i++) {
values.add(i, null);
im[i] = -1;
pm[i] = -1;
}
}
/**
* Given an index value it returns a map Key
* TODO: Improve the O(n) time complexity for this operation
*
* @param ki int
* @return K
*/
private K getMapKey(int ki) {
for (Map.Entry<K, Integer> entry : map.entrySet()) {
if (entry.getValue().equals(ki)) {
return entry.getKey();
}
}
return null;
}
/**
* Takes a node index as input and returns the index of the child with the lower value
* Returns '-1' in case one of the children does not exist
*
* @param i int
* @return int
*/
private int getLowerValueChildIndex(int i) {
V leftChild = getLeftChild(i);
V rightChild = getRightChild(i);
if (leftChild != null && rightChild != null) {
return leftChild.compareTo(rightChild) <= 0 ? (2 * i) + 1 : (2 * i) + 2;
} else if (leftChild == null && rightChild != null) {
return (2 * i) + 2;
} else if (leftChild != null) {
return (2 * i) + 1;
}
return -1;
}
/**
* Returns the left child's value of the given node
*
* @param index int
* @return T
*/
private V getLeftChild(int index) {
try {
return values.get(im[(index * 2) + 1]);
} catch (Exception e) {
return null;
}
}
/**
* Returns the right child's value of the given node
*
* @param index int
* @return T
*/
private V getRightChild(int index) {
try {
return values.get(im[(index * 2) + 2]);
} catch (Exception e) {
return null;
}
}
}