Implementation of heap (priority queue) in Java. Nothing fundamentally hard; the idea of visualizing an array to a tree is neat.

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
import java.util.*;
import java.util.stream.Collectors;

public class Main {
static class Heap {
// the logic size of heap
private int length;
private int[] arr;

// assert x in [low, max)
private static void assert_range(int x, int low, int max) {
assert (low <= x && x < max);
}

private void swap(int i, int j) {
assert_range(i, 0, length);
assert_range(j, 0, length);
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

// assuming left and right subtree are max-heap already;
// O(logN): depth of the tree
private void maxHeapify(int i) {
assert_range(i, 0, length);
var largest = i;
var left = 2 * i + 1;
var right = 2 * i + 2;
if (left < length && arr[left] > arr[largest])
largest = left;
if (right < length && arr[right] > arr[largest])
largest = right;

if (largest != i) {
// fix the violation
swap(i, largest);
maxHeapify(largest);
}
}

// it seems O(NlogN), but it's actually O(N), since #nodes per level
// drops exponentially, while the depth grows linearly
private Heap(int[] arr) {
length = arr.length;
this.arr = arr;
// working bottom-up;
for (int i = length / 2 - 1; i >= 0; i--) {
maxHeapify(i);
}
verify();
}

private void verify(int i) {
assert (i < length);
var left = 2 * i + 1;
var right = 2 * i + 2;
if (left < length) {
assert (arr[i] >= arr[left]);
verify(left);
}
if (right < length) {
assert (arr[i] >= arr[right]);
verify(right);
}
}

private void verify() {
if (length != 0) {
verify(0);
}
}

// O(1)
public boolean isEmpty() {
return length == 0;
}

// O(logN)
public int poll() {
assert (!isEmpty());
var ret = arr[0];
if (length > 1) {
swap(0, length - 1);
length--;
maxHeapify(0);
} else {
length--;
}
verify();
return ret;
}

// O(logN)
public void add(int e) {
if (length == arr.length) {
// expand underlying array
arr = Arrays.copyOf(arr, arr.length + 100);
}
arr[length++] = e;
// fix potential violation; go up level by level
var i = length - 1;
int parent;
while (true) {
parent = (i - 1) / 2;
if (i == 0 || arr[parent] >= arr[i]) break;
swap(parent, i);
i = parent;
}
verify();
}

public static Heap fromArrayInplace(int[] arr) {
return new Heap(arr);
}

public static Heap fromArray(int[] arr) {
return new Heap(arr.clone());
}

// heap sort inplace
public static void heapSort(int[] arr) {
var heap = fromArrayInplace(arr);
while (heap.length > 1) {
// first element is the largest; place it in the end
heap.swap(0, heap.length - 1);
// logically shrinking the heap
heap.length--;
// fix potential violation
heap.maxHeapify(0);
}
}
}

static class QCRunner {
static final int TESTMAX = 100000;
static Random rand = new Random();

static int[] generate_ints() {
return rand.ints(rand.nextInt(10) + 1).toArray();
}

static void qc_heap_sort() {
for (int i = 0; i < TESTMAX; ++i) {
var o_arr = generate_ints();
var a_arr = o_arr.clone();
Arrays.sort(a_arr);
var b_arr = o_arr.clone();
Heap.heapSort(b_arr);
assert (Arrays.equals(a_arr, b_arr));
}
}

static void qc_heap_poll() {
for (int i = 0; i < TESTMAX; ++i) {
var o_arr = generate_ints();
var a_queue = new PriorityQueue<Integer>(o_arr.length, Collections.reverseOrder());
a_queue.addAll(Arrays.stream(o_arr).boxed().collect(Collectors.toList()));
var b_queue = Heap.fromArray(o_arr);
while (!a_queue.isEmpty()) {
var a = a_queue.poll();
var b = b_queue.poll();
assert (a == b);
}
assert (b_queue.isEmpty());
}
}

static void qc_heap_add() {
for (int i = 0; i < TESTMAX; ++i) {
var o_arr = generate_ints();
var a_queue = new PriorityQueue<Integer>(o_arr.length, Collections.reverseOrder());
var b_queue = Heap.fromArray(new int[0]);
for (var e : o_arr) {
a_queue.add(e);
b_queue.add(e);
}
while (!a_queue.isEmpty()) {
var a = a_queue.poll();
var b = b_queue.poll();
assert (a == b);
}
assert (b_queue.isEmpty());
}
}

void main() {
qc_heap_sort();
qc_heap_poll();
qc_heap_add();
System.out.println("Success");
}
}

public static void main(String[] args) throws Exception {
ClassLoader loader = ClassLoader.getSystemClassLoader();
loader.setDefaultAssertionStatus(true);
var runner = (QCRunner) Class.forName("Main$QCRunner", true, loader)
.getDeclaredConstructor().newInstance();
runner.main();
}
}

ΒΆreferences