-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxPriorityQueue.java
82 lines (68 loc) · 1.89 KB
/
MaxPriorityQueue.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
// Uses a variable-sized array as a heap, where the item at
// index i is the parent of the items at 2i and 2i+1.
public class MaxPriorityQueue<T extends Comparable<T>> {
private T[] arr;
private int size;
public MaxPriorityQueue() {
return MaxPriorityQueue(10);
}
public MaxPriorityQueue(int startCapacity) {
arr = (T[]) new Comparable[startCapacity+1];
}
public boolean isEmpty() {
return size == 0;
}
public void insert(T item) {
// if out of space in the array, replace it with larger
if (arr.length-1 < ++size) {
T[] bigger = (T[]) new Comparable[2*size];
for (int i = 0; i < arr.length; i++) {
bigger[i] = arr[i];
}
arr = bigger;
}
// insert new item
arr[size] = item;
swim(size);
}
public T takeMax() {
// pull out max value
T max = arr[1];
swap(1, size--);
sink(1);
arr[size+1] = null;
// if data takes up less than 1/4 of the array, shrink it
if (size < arr.length/4) {
T[] smaller = (T[]) new Comparable[2*size];
for (int i = 0; i <= size; i++) {
smaller[i] = arr[i];
}
arr = smaller;
}
return max;
}
private boolean less(int i, int j) {
return arr[i].compareTo(arr[j]) < 0;
}
private void swap(int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private void swim(int i) {
while (i > 1 && less(i/2, i)) {
swap(i, i/2);
i = i/2;
}
}
private void sink(int i) {
int j;
while (i*2 <= size) {
j = i*2;
if (j < size && less(j, j+1)) { j++; }
if (!less(i, j)) break;
swap(i, j);
i = j;
}
}
}