-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGenericHeap.java
More file actions
70 lines (58 loc) · 1.31 KB
/
GenericHeap.java
File metadata and controls
70 lines (58 loc) · 1.31 KB
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
package lecture9a22;
import java.util.ArrayList;
public class GenericHeap<T extends Comparable<T>> {
ArrayList<T> data = new ArrayList<>();
public int size() {
return this.data.size();
}
public void add(T item) {
this.data.add(item);
upheapify(this.size() - 1);
}
private void upheapify(int ci) {
int pi = (ci - 1) / 2;
if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) {
swap(ci, pi);
upheapify(pi);
}
}
private void swap(int i, int j) {
T ith = this.data.get(i);
T jth = this.data.get(j);
this.data.set(i, jth);
this.data.set(j, ith);
}
public T remove() {
swap(0, this.size() - 1);
T rv = this.data.remove(this.size() - 1);
downheapify(0);
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(this.data.get(lci), this.data.get(mini)) > 0) {
mini = lci;
}
if (rci < this.data.size() && isLarger(this.data.get(rci), this.data.get(mini)) > 0) {
mini = rci;
}
if (mini != pi) {
swap(mini, pi);
downheapify(mini);
}
}
private int isLarger(T o1, T o2) {
return o1.compareTo(o2);
}
public void display() {
System.out.println(this.data);
}
public T getHP() {
return this.data.get(0);
}
public boolean isEmpty() {
return this.data.size() == 0;
}
}