-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
98 lines (86 loc) · 2.82 KB
/
Heap.java
File metadata and controls
98 lines (86 loc) · 2.82 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
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
import java.util.*;
public class Heap<T extends Comparable<T>> {
private ArrayList<T> heap = new ArrayList<>();
private Boolean type;
public Heap(Boolean type){
this.type = type;
}
public int size(){
return heap.size();
}
private int parent(int node){
return ( node - 1 ) / 2;
}
private int leftChild(int node){
int child = 2 * node + 1;
return child < size() ? child : -1;
}
private int rightChild(int node){
int child = 2 * node + 2;
return child < size() ? child : -1;
}
public T top(){
return size() > 1 ? heap.get(0) : null;
}
public void insert(T node){
heap.add(node);
trickleUp(size() - 1);
}
public T remove(){
if(size() == 0)
return null;
Collections.swap(heap, 0, size()-1);
T temp = heap.get(size() - 1);
heap.remove(size() - 1);
trickleDown(0);
return temp;
}
private void trickleUp(int node){
if(node == 0 || (type ? heap.get(parent(node)).compareTo(heap.get(node)) > 0:heap.get(parent(node)).compareTo(heap.get(node))<0))
return;
Collections.swap(heap, node, parent(node));
trickleUp(parent(node));
}
private void trickleDown(int node){
int leftChild = leftChild(node);
if(leftChild == -1)
return;
int rightChild = rightChild(node);
if(rightChild == -1){
if(type ? heap.get(node).compareTo(heap.get(leftChild)) < 0:heap.get(node).compareTo(heap.get(leftChild)) > 0){
Collections.swap(heap, node, leftChild);
trickleDown(leftChild);
}
}else{
int swappedChild;
if(type){
int maxChild = heap.get(rightChild).compareTo(heap.get(leftChild)) > 0 ? rightChild:leftChild;
if(heap.get(maxChild).compareTo(heap.get(node)) > 0){
Collections.swap(heap, maxChild, node);
trickleDown(maxChild);
}
}else{
int minChild = heap.get(rightChild).compareTo(heap.get(leftChild)) < 0 ? rightChild:leftChild;
if(heap.get(minChild).compareTo(heap.get(node)) < 0){
Collections.swap(heap, minChild, node);
trickleDown(minChild);
}
}
}
}
public static void main(String args[]){
//false is minHeap, true is maxHeap
Heap<Integer> heap = new Heap<Integer>(false);
heap.insert(1);
heap.insert(7);
heap.insert(8);
heap.insert(9);
heap.remove();
heap.insert(11);
heap.remove();
heap.insert(2);
heap.insert(3);
while(heap.size() != 0)
System.out.println(heap.remove());
}
}