-
Notifications
You must be signed in to change notification settings - Fork 18
/
BinaryHeap.java
337 lines (310 loc) · 8.11 KB
/
BinaryHeap.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
/**
* Copyright 2022 jingedawang
*/
package container;
import utils.ArrayGenerator;
import utils.ArrayPrinter;
/**
* BinaryHeap is basically a binary tree, whose each sub-tree keeps the max or min value in the root node.
*
* The underlying data is stored in an array, which is good for quick access.
* After the heap is built, the values are stored layer by layer in the array. For example, an array
* [4, 8, 1, 2, 0, 6, 5, 1, 9, 3]
* represents a heap like
* <pre>
* +--------------0---------------+
* +------1-------+ +------1-------+
* +--2---+ +--3---+ +--6---+ +--5---+
* 4 9 8
* </pre>
* To save time, we won't maintain a tree structure all the time. If you need to access the data by traversing
* its nodes, please call {@code toBinaryTree} method, which will return as a structured binary tree.
*/
public class BinaryHeap extends AbstractTree implements BinaryTree, Heap {
/**
* Demo code.
*/
public static void main(String[] args) {
int[] arr = ArrayGenerator.fixedArray();
System.out.println("Array used to build binary heap:");
ArrayPrinter.print(arr);
BinaryHeap heap = new BinaryHeap(arr, true);
System.out.println("The top value of the binary heap is:");
System.out.println(heap.top());
System.out.println("Pop values from the binary heap:");
while (heap.size() > 1) {
System.out.print(heap.pop() + ", ");
}
System.out.println(heap.pop());
}
/**
* Construct an empty max heap.
*/
public BinaryHeap() {
this(new int[0], false);
}
/**
* Construct a heap with given array.
*
* @param arr The data used for constructing the heap.
* @param isMinHeap A flag indicating whether to create a min heap or a max heap.
*/
public BinaryHeap(int[] arr, boolean isMinHeap) {
this.isMinHeap = isMinHeap;
data = arr.clone();
capacity = data.length;
size = data.length;
for (int i = size / 2 - 1; i >= 0; i--) {
if (isMinHeap) {
minHeapify(i);
} else {
maxHeapify(i);
}
}
}
/**
* Check if the heap has no elements.
*
* @return {@code true} if the heap has no elements, {@code false} otherwise.
*/
@Override
public boolean empty() {
return size == 0;
}
/**
* Get the size of the heap.
*
* @return The element count of the heap.
*/
@Override
public int size() {
return size;
}
/**
* Get the top value of the heap.
*
* If this is a max heap, the return value is the maximum.
* If this is a min heap, the return value is the minimum.
*
* @return The top value of the heap.
*/
@Override
public int top() {
return data[0];
}
/**
* Insert a node into the heap.
*
* The node will be inserted to a proper location in the heap.
* @param newNode The node to be inserted.
*/
@Override
public void insert(Node newNode) {
if (size >= capacity) {
int[] newArr;
if (capacity > 0) {
newArr = new int[capacity * 2];
System.arraycopy(data, 0, newArr, 0, size);
} else {
newArr = new int[8];
}
data = newArr;
capacity = newArr.length;
}
size++;
if (isMinHeap) {
data[size - 1] = Integer.MAX_VALUE;
decreaseValue(size - 1, newNode.value);
}
else {
data[size - 1] = Integer.MIN_VALUE;
increaseValue(size - 1, newNode.value);
}
}
/**
* Delete a node from the heap.
*
* Since the heap doesn't maintain the tree structure, so deleting a node from a heap is meaningless. Also, it's not
* useful to delete a node from a heap.
*
* @param node The node to be deleted.
*/
@Override
public void delete(Node node) {
throw new UnsupportedOperationException("'delete' method not supported in BinaryHeap class");
}
/**
* Get and remove the top value of the heap.
*
* If this is a max heap, the return value is the maximum.
* If this is a min heap, the return value is the minimum.
* The top node will be removed and the heap will be maintained.
*
* @return The top value of the heap.
*/
@Override
public int pop() {
if (size <= 0) {
throw new ArrayIndexOutOfBoundsException("Can not pop a value from an empty heap.");
}
int top = data[0];
data[0] = data[size - 1];
size--;
if (isMinHeap) {
minHeapify(0);
}
else {
maxHeapify(0);
}
return top;
}
/**
* Construct the tree structure and return as a binary tree.
*
* @return A binary tree converted from the heap.
*/
public BinaryTree toBinaryTree() {
root = constructSubtree(0);
return this;
}
/**
* Adjust the maximum sub-heap to maintain its properties.
*
* @param index The root index of the sub-heap.
*/
private void maxHeapify(int index) {
int l = left(index);
int r = right(index);
int largest;
if (l < size && data[l] > data[index]) {
largest = l;
} else {
largest = index;
}
if (r < size && data[r] > data[largest]) {
largest = r;
}
if (largest != index) {
int temp = data[index];
data[index] = data[largest];
data[largest] = temp;
maxHeapify(largest);
}
}
/**
* Adjust the minimum sub-heap to maintain its properties.
*
* @param index The root index of the sub-heap.
*/
private void minHeapify(int index) {
int l = left(index);
int r = right(index);
int smallest;
if (l < size && data[l] < data[index]) {
smallest = l;
} else {
smallest = index;
}
if (r < size && data[r] < data[smallest]) {
smallest = r;
}
if (smallest != index) {
int temp = data[index];
data[index] = data[smallest];
data[smallest] = temp;
minHeapify(smallest);
}
}
/**
* Increase the value of the specified item and adjust the heap to keep its properties.
* <p>
* The new value must be greater than the original value, or this method would raise an error.
* This method should be called from a max heap.
*
* @param index The index of the specified item.
* @param newValue The new value of the specified item.
*/
private void increaseValue(int index, int newValue) {
if (newValue < data[index]) {
throw new IllegalArgumentException("Only increasing value is allowed.");
}
data[index] = newValue;
while (index > 0 && data[index] > data[parent(index)]) {
int temp = data[index];
data[index] = data[parent(index)];
data[parent(index)] = temp;
index = parent(index);
}
}
/**
* Decrease the value of the specified item and adjust the heap to keep its properties.
* <p>
* The new value must be smaller than the original value, or this method would raise an error.
* This method should be called from a min heap.
*
* @param index The index of the specified item.
* @param newValue The new value of the specified item.
*/
private void decreaseValue(int index, int newValue) {
if (newValue > data[index]) {
throw new IllegalArgumentException("Only decreasing value is allowed.");
}
data[index] = newValue;
while (index > 0 && data[index] < data[parent(index)]) {
int temp = data[index];
data[index] = data[parent(index)];
data[parent(index)] = temp;
index = parent(index);
}
}
/**
* Get the index of the parent node.
*
* @param i The index of the given node.
* @return The index of the parent node.
*/
private int parent(int i) {
return (i - 1) / 2;
}
/**
* Get the index of the left child node.
*
* @param i The index of the given node.
* @return The index of the left child node.
*/
private int left(int i) {
return 2 * i + 1;
}
/**
* Get the index of the right child node.
*
* @param i The index of the given node.
* @return The index of the right child node.
*/
private int right(int i) {
return 2 * (i + 1);
}
/**
* Construct tree structure recursively.
*
* @param index The index of the subtree to be constructed.
* @return The root node of the constructed subtree.
*/
private Node constructSubtree(int index) {
if (index >= size()) {
return null;
}
Node root = new Node(data[index]);
root.left = constructSubtree(left(index));
root.right = constructSubtree(right(index));
return root;
}
// Flag to indicate whether this heap is a min heap or a max heap.
private final boolean isMinHeap;
// Underlying array data.
private int[] data;
// The number of elements in this heap.
private int size;
// The capacity of this heap.
public int capacity;
}