-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
MinIndexedDHeap.java
253 lines (209 loc) · 6.48 KB
/
MinIndexedDHeap.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
/**
* An implementation of an indexed min D-ary heap priority queue.
*
* <p>This implementation supports arbitrary keys with comparable values. To use arbitrary keys
* (such as strings or objects) first map all your keys to the integer domain [0, N) where N is the
* number of keys you have and then use the mapping with this indexed priority queue.
*
* <p>As convention, I denote 'ki' as the index value in the domain [0, N) associated with a key k,
* therefore: ki = map[k]
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.datastructures.priorityqueue;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class MinIndexedDHeap<T extends Comparable<T>> {
// Current number of elements in the heap.
private int sz;
// Maximum number of elements in the heap.
private final int N;
// The degree of every node in the heap.
private final int D;
// Lookup arrays to track the child/parent indexes of each node.
private final int[] child, parent;
// The Position Map (pm) maps Key Indexes (ki) to where the position of that
// key is represented in the priority queue in the domain [0, sz).
public final int[] pm;
// The Inverse Map (im) stores the indexes of the keys in the range
// [0, sz) which make up the priority queue. It should be noted that
// 'im' and 'pm' are inverses of each other, so: pm[im[i]] = im[pm[i]] = i
public final int[] im;
// The values associated with the keys. It is very important to note
// that this array is indexed by the key indexes (aka 'ki').
public final Object[] values;
// Initializes a D-ary heap with a maximum capacity of maxSize.
public MinIndexedDHeap(int degree, int maxSize) {
if (maxSize <= 0) throw new IllegalArgumentException("maxSize <= 0");
D = max(2, degree);
N = max(D + 1, maxSize);
im = new int[N];
pm = new int[N];
child = new int[N];
parent = new int[N];
values = new Object[N];
for (int i = 0; i < N; i++) {
parent[i] = (i - 1) / D;
child[i] = i * D + 1;
pm[i] = im[i] = -1;
}
}
public int size() {
return sz;
}
public boolean isEmpty() {
return sz == 0;
}
public boolean contains(int ki) {
keyInBoundsOrThrow(ki);
return pm[ki] != -1;
}
public int peekMinKeyIndex() {
isNotEmptyOrThrow();
return im[0];
}
public int pollMinKeyIndex() {
int minki = peekMinKeyIndex();
delete(minki);
return minki;
}
@SuppressWarnings("unchecked")
public T peekMinValue() {
isNotEmptyOrThrow();
return (T) values[im[0]];
}
public T pollMinValue() {
T minValue = peekMinValue();
delete(peekMinKeyIndex());
return minValue;
}
public void insert(int ki, T value) {
if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki);
valueNotNullOrThrow(value);
pm[ki] = sz;
im[sz] = ki;
values[ki] = value;
swim(sz++);
}
@SuppressWarnings("unchecked")
public T valueOf(int ki) {
keyExistsOrThrow(ki);
return (T) values[ki];
}
@SuppressWarnings("unchecked")
public T delete(int ki) {
keyExistsOrThrow(ki);
final int i = pm[ki];
swap(i, --sz);
sink(i);
swim(i);
T value = (T) values[ki];
values[ki] = null;
pm[ki] = -1;
im[sz] = -1;
return value;
}
@SuppressWarnings("unchecked")
public T update(int ki, T value) {
keyExistsAndValueNotNullOrThrow(ki, value);
final int i = pm[ki];
T oldValue = (T) values[ki];
values[ki] = value;
sink(i);
swim(i);
return oldValue;
}
// Strictly decreases the value associated with 'ki' to 'value'
public void decrease(int ki, T value) {
keyExistsAndValueNotNullOrThrow(ki, value);
if (less(value, values[ki])) {
values[ki] = value;
swim(pm[ki]);
}
}
// Strictly increases the value associated with 'ki' to 'value'
public void increase(int ki, T value) {
keyExistsAndValueNotNullOrThrow(ki, value);
if (less(values[ki], value)) {
values[ki] = value;
sink(pm[ki]);
}
}
/* Helper functions */
private void sink(int i) {
for (int j = minChild(i); j != -1; ) {
swap(i, j);
i = j;
j = minChild(i);
}
}
private void swim(int i) {
while (less(i, parent[i])) {
swap(i, parent[i]);
i = parent[i];
}
}
// From the parent node at index i find the minimum child below it
private int minChild(int i) {
int index = -1, from = child[i], to = min(sz, from + D);
for (int j = from; j < to; j++) if (less(j, i)) index = i = j;
return index;
}
private void swap(int i, int j) {
pm[im[j]] = i;
pm[im[i]] = j;
int tmp = im[i];
im[i] = im[j];
im[j] = tmp;
}
// Tests if the value of node i < node j
@SuppressWarnings("unchecked")
private boolean less(int i, int j) {
return ((Comparable<? super T>) values[im[i]]).compareTo((T) values[im[j]]) < 0;
}
@SuppressWarnings("unchecked")
private boolean less(Object obj1, Object obj2) {
return ((Comparable<? super T>) obj1).compareTo((T) obj2) < 0;
}
@Override
public String toString() {
List<Integer> lst = new ArrayList<>(sz);
for (int i = 0; i < sz; i++) lst.add(im[i]);
return lst.toString();
}
/* Helper functions to make the code more readable. */
private void isNotEmptyOrThrow() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
}
private void keyExistsAndValueNotNullOrThrow(int ki, Object value) {
keyExistsOrThrow(ki);
valueNotNullOrThrow(value);
}
private void keyExistsOrThrow(int ki) {
if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki);
}
private void valueNotNullOrThrow(Object value) {
if (value == null) throw new IllegalArgumentException("value cannot be null");
}
private void keyInBoundsOrThrow(int ki) {
if (ki < 0 || ki >= N)
throw new IllegalArgumentException("Key index out of bounds; received: " + ki);
}
/* Test functions */
// Recursively checks if this heap is a min heap. This method is used
// for testing purposes to validate the heap invariant.
public boolean isMinHeap() {
return isMinHeap(0);
}
private boolean isMinHeap(int i) {
int from = child[i], to = min(sz, from + D);
for (int j = from; j < to; j++) {
if (!less(i, j)) return false;
if (!isMinHeap(j)) return false;
}
return true;
}
}