-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayHeap.java
executable file
·417 lines (364 loc) · 12.5 KB
/
ArrayHeap.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import org.junit.Test;
import static org.junit.Assert.*;
/**
* A Generic heap class. Unlike Java's priority queue, this heap doesn't just
* store Comparable objects. Instead, it can store any type of object
* (represented by type T), along with a priority value. Why do it this way? It
* will be useful later on in the class...
*/
public class ArrayHeap<T> implements ExtrinsicPQ<T> {
private Node[] contents;
private int size;
public ArrayHeap() {
contents = new ArrayHeap.Node[16];
/* Add a dummy item at the front of the ArrayHeap so that the getLeft,
* getRight, and parent methods are nicer. */
contents[0] = null;
/* Even though there is an empty spot at the front, we still consider
* the size to be 0 since nothing has been inserted yet. */
size = 0;
}
/**
* Returns the index of the node to the left of the node at i.
*/
private static int leftIndex(int i) {
/* TODO: Your code here! */
return 0;
}
/**
* Returns the index of the node to the right of the node at i.
*/
private static int rightIndex(int i) {
/* TODO: Your code here! */
return 0;
}
/**
* Returns the index of the node that is the parent of the node at i.
*/
private static int parentIndex(int i) {
/* TODO: Your code here! */
return 0;
}
/**
* Gets the node at the ith index, or returns null if the index is out of
* bounds.
*/
private Node getNode(int index) {
if (!inBounds(index)) {
return null;
}
return contents[index];
}
/**
* Returns true if the index corresponds to a valid item. For example, if
* we have 5 items, then the valid indices are 1, 2, 3, 4, 5. Index 0 is
* invalid because we leave the 0th entry blank.
*/
private boolean inBounds(int index) {
if ((index > size) || (index < 1)) {
return false;
}
return true;
}
/**
* Swap the nodes at the two indices.
*/
private void swap(int index1, int index2) {
Node node1 = getNode(index1);
Node node2 = getNode(index2);
contents[index1] = node2;
contents[index2] = node1;
}
/**
* Returns the index of the node with smaller priority. Precondition: not
* both nodes are null.
*/
private int min(int index1, int index2) {
Node node1 = getNode(index1);
Node node2 = getNode(index2);
if (node1 == null) {
return index2;
} else if (node2 == null) {
return index1;
} else if (node1.myPriority < node2.myPriority) {
return index1;
} else {
return index2;
}
}
/**
* Bubbles up the node currently at the given index.
*/
private void swim(int index) {
// Throws an exception if index is invalid. DON'T CHANGE THIS LINE.
validateSinkSwimArg(index);
/** TODO: Your code here. */
return;
}
/**
* Bubbles down the node currently at the given index.
*/
private void sink(int index) {
// Throws an exception if index is invalid. DON'T CHANGE THIS LINE.
validateSinkSwimArg(index);
/** TODO: Your code here. */
return;
}
/**
* Inserts an item with the given priority value. This is enqueue, or offer.
* To implement this method, add it to the end of the ArrayList, then swim it.
*/
@Override
public void insert(T item, double priority) {
/* If the array is totally full, resize. */
if (size + 1 == contents.length) {
resize(contents.length * 2);
}
/* TODO: Your code here! */
}
/**
* Returns the Node with the smallest priority value, but does not remove it
* from the heap. To implement this, return the item in the 1st position of the ArrayList.
*/
@Override
public T peek() {
/* TODO: Your code here! */
return null;
}
/**
* Returns the Node with the smallest priority value, and removes it from
* the heap. This is dequeue, or poll. To implement this, swap the last
* item from the heap into the root position, then sink the root. This is
* equivalent to firing the president of the company, taking the last
* person on the list on payroll, making them president, and then demoting
* them repeatedly. Make sure to avoid loitering by nulling out the dead
* item.
*/
@Override
public T removeMin() {
/* TODO: Your code here! */
return null;
}
/**
* Returns the number of items in the PQ. This is one less than the size
* of the backing ArrayList because we leave the 0th element empty. This
* method has been implemented for you.
*/
@Override
public int size() {
return size;
}
/**
* Change the node in this heap with the given item to have the given
* priority. You can assume the heap will not have two nodes with the same
* item. Check item equality with .equals(), not ==. This is a challenging
* bonus problem, but shouldn't be too hard if you really understand heaps
* and think about the algorithm before you start to code.
*/
@Override
public void changePriority(T item, double priority) {
/* TODO: Your code here! */
return;
}
/**
* Prints out the heap sideways. Provided for you.
*/
@Override
public String toString() {
return toStringHelper(1, "");
}
/* Recursive helper method for toString. */
private String toStringHelper(int index, String soFar) {
if (getNode(index) == null) {
return "";
} else {
String toReturn = "";
int rightChild = rightIndex(index);
toReturn += toStringHelper(rightChild, " " + soFar);
if (getNode(rightChild) != null) {
toReturn += soFar + " /";
}
toReturn += "\n" + soFar + getNode(index) + "\n";
int leftChild = leftIndex(index);
if (getNode(leftChild) != null) {
toReturn += soFar + " \\";
}
toReturn += toStringHelper(leftChild, " " + soFar);
return toReturn;
}
}
/**
* Throws an exception if the index is invalid for sinking or swimming.
*/
private void validateSinkSwimArg(int index) {
if (index < 1) {
throw new IllegalArgumentException("Cannot sink or swim nodes with index 0 or less");
}
if (index > size) {
throw new IllegalArgumentException("Cannot sink or swim nodes with index greater than current size.");
}
if (contents[index] == null) {
throw new IllegalArgumentException("Cannot sink or swim a null node.");
}
}
private class Node {
private T myItem;
private double myPriority;
private Node(T item, double priority) {
myItem = item;
myPriority = priority;
}
public T item(){
return myItem;
}
public double priority() {
return myPriority;
}
@Override
public String toString() {
return myItem.toString() + ", " + myPriority;
}
}
/** Helper function to resize the backing array when necessary. */
private void resize(int capacity) {
Node[] temp = new ArrayHeap.Node[capacity];
for (int i = 1; i < this.contents.length; i++) {
temp[i] = this.contents[i];
}
this.contents = temp;
}
@Test
public void testIndexing() {
assertEquals(6, leftIndex(3));
assertEquals(10, leftIndex(5));
assertEquals(7, rightIndex(3));
assertEquals(11, rightIndex(5));
assertEquals(3, parentIndex(6));
assertEquals(5, parentIndex(10));
assertEquals(3, parentIndex(7));
assertEquals(5, parentIndex(11));
}
@Test
public void testSwim() {
ArrayHeap<String> pq = new ArrayHeap<>();
pq.size = 7;
for (int i = 1; i <= 7; i += 1) {
pq.contents[i] = new ArrayHeap<String>.Node("x" + i, i);
}
// Change item x6's priority to a low value.
pq.contents[6].myPriority = 0;
System.out.println("PQ before swimming:");
System.out.println(pq);
// Swim x6 upwards. It should reach the root.
pq.swim(6);
System.out.println("PQ after swimming:");
System.out.println(pq);
assertEquals("x6", pq.contents[1].myItem);
assertEquals("x2", pq.contents[2].myItem);
assertEquals("x1", pq.contents[3].myItem);
assertEquals("x4", pq.contents[4].myItem);
assertEquals("x5", pq.contents[5].myItem);
assertEquals("x3", pq.contents[6].myItem);
assertEquals("x7", pq.contents[7].myItem);
}
@Test
public void testSink() {
ArrayHeap<String> pq = new ArrayHeap<>();
pq.size = 7;
for (int i = 1; i <= 7; i += 1) {
pq.contents[i] = new ArrayHeap<String>.Node("x" + i, i);
}
// Change root's priority to a large value.
pq.contents[1].myPriority = 10;
System.out.println("PQ before sinking:");
System.out.println(pq);
// Sink the root.
pq.sink(1);
System.out.println("PQ after sinking:");
System.out.println(pq);
assertEquals("x2", pq.contents[1].myItem);
assertEquals("x4", pq.contents[2].myItem);
assertEquals("x3", pq.contents[3].myItem);
assertEquals("x1", pq.contents[4].myItem);
assertEquals("x5", pq.contents[5].myItem);
assertEquals("x6", pq.contents[6].myItem);
assertEquals("x7", pq.contents[7].myItem);
}
@Test
public void testInsert() {
ArrayHeap<String> pq = new ArrayHeap<>();
pq.insert("c", 3);
assertEquals("c", pq.contents[1].myItem);
pq.insert("i", 9);
assertEquals("i", pq.contents[2].myItem);
pq.insert("g", 7);
pq.insert("d", 4);
assertEquals("d", pq.contents[2].myItem);
pq.insert("a", 1);
assertEquals("a", pq.contents[1].myItem);
pq.insert("h", 8);
pq.insert("e", 5);
pq.insert("b", 2);
pq.insert("c", 3);
pq.insert("d", 4);
System.out.println("pq after inserting 10 items: ");
System.out.println(pq);
assertEquals(10, pq.size());
assertEquals("a", pq.contents[1].myItem);
assertEquals("b", pq.contents[2].myItem);
assertEquals("e", pq.contents[3].myItem);
assertEquals("c", pq.contents[4].myItem);
assertEquals("d", pq.contents[5].myItem);
assertEquals("h", pq.contents[6].myItem);
assertEquals("g", pq.contents[7].myItem);
assertEquals("i", pq.contents[8].myItem);
assertEquals("c", pq.contents[9].myItem);
assertEquals("d", pq.contents[10].myItem);
}
@Test
public void testInsertAndRemoveOnce() {
ArrayHeap<String> pq = new ArrayHeap<>();
pq.insert("c", 3);
pq.insert("i", 9);
pq.insert("g", 7);
pq.insert("d", 4);
pq.insert("a", 1);
pq.insert("h", 8);
pq.insert("e", 5);
pq.insert("b", 2);
pq.insert("c", 3);
pq.insert("d", 4);
String removed = pq.removeMin();
assertEquals("a", removed);
assertEquals(9, pq.size());
assertEquals("b", pq.contents[1].myItem);
assertEquals("c", pq.contents[2].myItem);
assertEquals("e", pq.contents[3].myItem);
assertEquals("c", pq.contents[4].myItem);
assertEquals("d", pq.contents[5].myItem);
assertEquals("h", pq.contents[6].myItem);
assertEquals("g", pq.contents[7].myItem);
assertEquals("i", pq.contents[8].myItem);
assertEquals("d", pq.contents[9].myItem);
}
@Test
public void testInsertAndRemoveAllButLast() {
ExtrinsicPQ<String> pq = new ArrayHeap<>();
pq.insert("c", 3);
pq.insert("i", 9);
pq.insert("g", 7);
pq.insert("d", 4);
pq.insert("a", 1);
pq.insert("h", 8);
pq.insert("e", 5);
pq.insert("b", 2);
pq.insert("c", 3);
pq.insert("d", 4);
int i = 0;
String[] expected = {"a", "b", "c", "c", "d", "d", "e", "g", "h", "i"};
while (pq.size() > 1) {
assertEquals(expected[i], pq.removeMin());
i += 1;
}
}
}