-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxHeap.java
66 lines (51 loc) · 1.31 KB
/
MaxHeap.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
public class MaxHeap {
final static int MAX_CAPACITY = 10000;
int[] heap;
int size = 0;
public static void main(String[] args) {
MaxHeap heap = new MaxHeap();
int[] values = {3, 1, 5, 7, 9, 2};
heap.buildHeap(values);
heap.printHeap();
}
public void buildHeap(int[] values) {
heap = new int[MAX_CAPACITY];
size = values.length;
for (int i = 0; i < size; ++i) {
heap[i] = values[i];
}
for (int i = size / 2; i >= 0; --i) {
restoreHeap(i);
}
}
public void printHeap() {
for (int i = 0; i < size; ++i) {
System.out.print(heap[i] + " ");
}
System.out.println();
}
private void restoreHeap(int i) {
while (2 * i + 1 < size) {
int j = 2 * i + 1;
if (j + 1 < size && heap[j] > heap[j + 1]) {
++j;
}
if (heap[i] < heap[j]) {
return;
}
swap(i, j);
i = j;
}
}
private void swap(int i, int j) {
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
public int popMax() {
int value = heap[0];
heap[0] = heap[--size];
restoreHeap(0);
return value;
}
}