-
Notifications
You must be signed in to change notification settings - Fork 1
/
MaxHeap.java
82 lines (76 loc) · 1.58 KB
/
MaxHeap.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
public class MaxHeap<E extends Comparable<E>> {
private Array<E> data;
public MaxHeap(int capacity) {
data=new Array<>(capacity);
}
public MaxHeap() {
data=new Array<>();
}
public MaxHeap(E[] arr) {
data=new Array<>(arr);
for(int i=parent(arr.length-1);i>=0;i--) {
siftDown(i);
}
}
public int size() {
return data.getSize();
}
public boolean isEmpty() {
return data.isEmpty();
}
private int parent(int index) {
if(index==0) {
throw new IllegalArgumentException("index-0 doesn't have parent");
}
return (index-1)/2;
}
private int leftChild(int index) {
return index*2+1;
}
private int rightChild(int index) {
return index*2+2;
}
public void add(E e) {
data.addLast(e);
siftUp(data.getSize()-1);
}
private void siftUp(int k) {
while(k>0&&data.get(parent(k)).compareTo(data.get(k))<0) {
data.swap(k, parent(k));
k=parent(k);
}
}
public E findMax() {
if(data.getSize()==0) {
throw new IllegalArgumentException("can not findmax whem heap is empty");
}
return data.get(0);
}
public E extractMax() {
E ret =findMax();
data.swap(0, data.getSize()-1);
data.removeLast();
siftDown(0);
return ret;
}
private void siftDown(int k) {
while(leftChild(k)<data.getSize()) {
int j=leftChild(k);
if(j+1<data.getSize()&&data.get(j+1).compareTo(data.get(j))>0){
j=rightChild(k);
}
if(data.get(k).compareTo(data.get(j))>0) {
break;
}
data.swap(k, j);
k=j;
}
}
// 取出最大元素后,放入一个新元素
public E replace(E e) {
E ret=findMax();
data.set(0, e);
siftDown(0);
return ret;
}
}