-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapPriorityQueue.java
264 lines (217 loc) · 5.83 KB
/
HeapPriorityQueue.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
package projectCode20280;
/*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
/**
* An implementation of a priority queue using an array-based heap.
*/
public class HeapPriorityQueue<K,V> extends AbstractPriorityQueue<K,V> {
protected ArrayList<Entry<K,V>> heap = new ArrayList<>();
/** Creates an empty priority queue based on the natural ordering of its keys. */
public HeapPriorityQueue() { super(); }
/**
* Creates an empty priority queue using the given comparator to order keys.
* @param comp comparator defining the order of keys in the priority queue
*/
public HeapPriorityQueue(Comparator<K> comp) { super(comp); }
/**
* Creates a priority queue initialized with the respective
* key-value pairs. The two arrays given will be paired
* element-by-element. They are presumed to have the same
* length. (If not, entries will be created only up to the length of
* the shorter of the arrays)
* @param keys an array of the initial keys for the priority queue
* @param values an array of the initial values for the priority queue
*/
public HeapPriorityQueue(K[] keys, V[] values)
{
super();
for (int j=0; j < Math.min(keys.length, values.length); j++)
{
heap.add(new PQEntry<>(keys[j], values[j]));
heapify();
}
}
// protected utilities
protected int parent(int j)
{
return (j-1)/2;
}
protected int left(int j)
{
return (2*j) + 1;
}
protected int right(int j)
{
return (2*j) + 2;
}
protected boolean hasLeft(int j)
{
return left(j) < heap.size();
}
protected boolean hasRight(int j)
{
return right(j) < heap.size();
}
/** Exchanges the entries at indices i and j of the array list. */
protected void swap(int i, int j)
{
Entry<K,V> temp = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, temp);
}
/** Moves the entry at index j higher, if necessary, to restore the heap property. */
protected void upheap(int j)
{
//bubble up the heap as long as condition holds
while (j > 0)
{
int p = parent(j);
if (compare(heap.get(j), heap.get(p)) >= 0)
{
break;
}
swap(j, p);
j = p;
}
}
/** Moves the entry at index j lower, if necessary, to restore the heap property. */
protected void downheap(int j)
{
while (hasLeft(j))
{
int leftIndex = left(j);
int smallChildIndex = leftIndex;
//check for right smaller
if (hasRight(j))
{
int rightIndex = right(j);
if (compare(heap.get(leftIndex), heap.get(rightIndex)) > 0)
{
smallChildIndex = rightIndex;
}
}
//move down if needed
if (compare(heap.get(smallChildIndex), heap.get(j)) >= 0)
{
break;
}
swap(j, smallChildIndex);
j = smallChildIndex;
}
}
/** Performs a bottom-up construction of the heap in linear time. */
protected void heapify()
{
int startIndex = parent(size() - 1);
for (int j = startIndex; j >= 0; j--)
{
downheap(j);
}
}
// public methods
/**
* Returns the number of items in the priority queue.
* @return number of items
*/
@Override
public int size() { return heap.size(); }
/**
* Returns (but does not remove) an entry with minimal key.
* @return entry having a minimal key (or null if empty)
*/
@Override
public Entry<K,V> min()
{
if (heap.isEmpty())
{
return null;
}
return heap.get(0);
}
/**
* Inserts a key-value pair and return the entry created.
* @param key the key of the new entry
* @param value the associated value of the new entry
* @return the entry storing the new key-value pair
* @throws IllegalArgumentException if the key is unacceptable for this queue
*/
@Override
public Entry<K,V> insert(K key, V value) throws IllegalArgumentException
{
checkKey(key);
Entry<K,V> newest = new PQEntry<>(key, value);
heap.add(newest);
upheap(heap.size() - 1);
return newest;
}
/**
* Removes and returns an entry with minimal key.
* @return the removed entry (or null if empty)
*/
@Override
public Entry<K,V> removeMin()
{
if (heap.isEmpty())
{
return null;
}
Entry<K,V> answer = heap.get(0);
swap(0, heap.size() - 1);
heap.remove(heap.size() - 1);
downheap(0);
return answer;
}
/** Used for debugging purposes only */
private void sanityCheck() {
for (int j=0; j < heap.size(); j++) {
int left = left(j);
int right = right(j);
if (left < heap.size() && compare(heap.get(left), heap.get(j)) < 0)
System.out.println("Invalid left child relationship");
if (right < heap.size() && compare(heap.get(right), heap.get(j)) < 0)
System.out.println("Invalid right child relationship");
}
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
for (Entry<K, V> entry : heap)
{
sb.append(entry);
sb.replace(sb.length()-1, sb.length(), "");
sb.append(", ");
}
sb.replace(sb.length()-2, sb.length(), "");
sb.append("]");
return sb.toString();
}
public static void main(String[] args)
{
HeapPriorityQueue<Integer, Integer> hpq = new HeapPriorityQueue<Integer, Integer>();
for (int i = 5; i > -1; i--)
{
hpq.insert(i, i);
}
System.out.println("Initial Heap: ");
System.out.println(hpq.toString());
System.out.println("Insert 30: ");
hpq.insert(30, 30);
System.out.println(hpq.toString());
System.out.println("Removing Minimum Key Element:");
hpq.removeMin();
System.out.println(hpq.toString());
System.out.println("Insert 4:");
hpq.insert(7, 7);
System.out.println(hpq.toString());
System.out.println("Insert -3");
hpq.insert(-3, -3);
System.out.println(hpq.toString());
System.out.println("Insert 5");
hpq.insert(-1, -1);
System.out.println(hpq.toString());
}
}