-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.java
101 lines (83 loc) Β· 1.52 KB
/
Heap.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
import java.util.ArrayList;
import java.util.HashMap;
public class Heap<T extends Comparable<T>>
{
ArrayList<T> data = new ArrayList<>();
HashMap<T, Integer> map = new HashMap<>();
public void add(T item)
{
data.add(item);
map.put(item, this.data.size() - 1);
upheapify(data.size() - 1);
}
private void upheapify(int ci)
{
int pi = (ci - 1) / 2;
if (isLarger(data.get(ci), data.get(pi)) > 0)
{
swap(pi, ci);
upheapify(pi);
}
}
private void swap(int i, int j)
{
T ith = data.get(i);
T jth = data.get(j);
data.set(i, jth);
data.set(j, ith);
map.put(ith, j);
map.put(jth, i);
}
public void display()
{
System.out.println(data);
}
public int size()
{
return this.data.size();
}
public boolean isEmpty()
{
return this.size() == 0;
}
public T remove()
{
swap(0, this.data.size() - 1);
T rv = this.data.remove(this.data.size() - 1);
downheapify(0);
map.remove(rv);
return rv;
}
private void downheapify(int pi)
{
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
int mini = pi;
if (lci < this.data.size() && isLarger(data.get(lci), data.get(mini)) > 0)
{
mini = lci;
}
if (rci < this.data.size() && isLarger(data.get(rci), data.get(mini)) > 0)
{
mini = rci;
}
if (mini != pi)
{
swap(mini, pi);
downheapify(mini);
}
}
public T get()
{
return this.data.get(0);
}
public int isLarger(T t, T o)
{
return t.compareTo(o);
}
public void updatePriority(T pair)
{
int index = map.get(pair);
upheapify(index);
}
}