forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryHeap.java
83 lines (73 loc) · 2.04 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
package structures;
import java.util.*;
// https://en.wikipedia.org/wiki/Binary_heap
// invariant: heap[parent] <= heap[child]
public class BinaryHeap {
int[] heap;
int size;
public BinaryHeap(int n) {
heap = new int[n];
}
// build heap in O(n)
public BinaryHeap(int[] values) {
heap = values.clone();
size = values.length;
for (int pos = size / 2 - 1; pos >= 0; pos--) down(pos);
}
public int removeMin() {
int removed = heap[0];
heap[0] = heap[--size];
down(0);
return removed;
}
public void add(int value) {
heap[size] = value;
up(size++);
}
void up(int pos) {
while (pos > 0) {
int parent = (pos - 1) / 2;
if (heap[pos] >= heap[parent])
break;
swap(pos, parent);
pos = parent;
}
}
void down(int pos) {
while (true) {
int child = 2 * pos + 1;
if (child >= size)
break;
if (child + 1 < size && heap[child + 1] < heap[child])
++child;
if (heap[pos] <= heap[child])
break;
swap(pos, child);
pos = child;
}
}
void swap(int i, int j) {
int t = heap[i];
heap[i] = heap[j];
heap[j] = t;
}
// random test
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 1000; step++) {
int n = rnd.nextInt(100) + 1;
PriorityQueue<Integer> q = new PriorityQueue<>();
BinaryHeap h = new BinaryHeap(n);
for (int op = 0; op < 1000; op++) {
if (rnd.nextBoolean() && q.size() < n) {
int v = rnd.nextInt();
q.add(v);
h.add(v);
} else if (!q.isEmpty()) {
if (q.remove() != h.removeMin())
throw new RuntimeException();
}
}
}
}
}