-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
63 lines (54 loc) · 1.36 KB
/
Copy pathHeap.java
File metadata and controls
63 lines (54 loc) · 1.36 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
import java.util.ArrayList;
public class Heap <E extends Comparable<E>>{
private ArrayList<E> list=new ArrayList<>();
public Heap(){
}
public Heap(E[] objects){
for(int i=0;i<objects.length;i++){
add(objects[i]);
}
}
public void add(E newObject){
list.add(newObject);
int currentIndex=list.size()-1;
while(currentIndex>0){
int parentIndex=(currentIndex-1)/2;
if(list.get(parentIndex).compareTo(newObject)<0){
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, newObject);
}
else break;
currentIndex=parentIndex;
}
}
public E remove(){
if(list.size()==0)
return null;
E rootObject=list.get(0);
int currentIndex=list.size()-1;
list.set(0, list.get(currentIndex));
list.remove(currentIndex);
currentIndex=0;
while(currentIndex<list.size()){
int leftChild=2*currentIndex+1;
int rightChild=2*currentIndex+2;
if(leftChild>=list.size())
break;
int maxIndex=leftChild;
if(rightChild<list.size()&&list.get(rightChild).compareTo(list.get(leftChild))>0)
maxIndex=rightChild;
if(list.get(currentIndex).compareTo(list.get(maxIndex))<0){
E t=list.get(currentIndex);
list.set(currentIndex, list.get(maxIndex));
list.set(maxIndex, t);
currentIndex=maxIndex;
}
else
break;
}
return rootObject;
}
public int getSize(){
return list.size();
}
}