forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeableHeap.java
67 lines (57 loc) · 1.42 KB
/
MergeableHeap.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
package structures;
import java.util.Random;
public class MergeableHeap {
static Random random = new Random();
public static class Heap {
int value;
Heap left;
Heap right;
Heap(int value) {
this.value = value;
}
}
public static Heap merge(Heap a, Heap b) {
if (a == null)
return b;
if (b == null)
return a;
if (a.value > b.value) {
Heap t = a;
a = b;
b = t;
}
if (random.nextBoolean()) {
Heap t = a.left;
a.left = a.right;
a.right = t;
}
a.left = merge(a.left, b);
return a;
}
public static Heap add(Heap h, int value) {
return merge(h, new Heap(value));
}
public static class HeapAndResult {
Heap heap;
int value;
HeapAndResult(Heap h, int value) {
this.heap = h;
this.value = value;
}
}
public static HeapAndResult removeMin(Heap h) {
return new HeapAndResult(merge(h.left, h.right), h.value);
}
// Usage example
public static void main(String[] args) {
Heap h = null;
h = add(h, 3);
h = add(h, 1);
h = add(h, 2);
while (h != null) {
HeapAndResult hv = removeMin(h);
System.out.println(hv.value);
h = hv.heap;
}
}
}