-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
65 lines (58 loc) · 1.97 KB
/
Heap.java
File metadata and controls
65 lines (58 loc) · 1.97 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
import java.util.ArrayList;
import java.util.NoSuchElementException;
/**
* Created by cdxu0 on 2017/7/6.
*/
public class Heap<E extends Comparable> {
private ArrayList<E> list = new ArrayList<E>();
public Heap() {
}
public Heap(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(E e) {
list.add(e);
int currentIndex = list.size()-1;
while (currentIndex > 0) {
int parentIndex = (currentIndex-1)/2;
if (list.get(currentIndex).compareTo(list.get(parentIndex)) > 0){
E temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
} else
break;
currentIndex = parentIndex;
}
}
public E remove() {
if (list.size() == 0)
return null;
E temp = list.get(0);
list.set(0, list.get(list.size()-1));
list.remove(list.size()-1);
int currentIndex = 0;
while (currentIndex<list.size()) {
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if (leftChildIndex >= list.size())
break;
int maxIndex = leftChildIndex;
if (rightChildIndex<list.size()) {
if (list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
if (list.get(currentIndex).compareTo(list.get(maxIndex)) < 0) {
E swap = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, swap);
currentIndex = maxIndex;
} else
break;
}
return temp;
}
public int getSize() {
return list.size();
}
}