-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHeap.java
More file actions
101 lines (86 loc) · 2.52 KB
/
MyHeap.java
File metadata and controls
101 lines (86 loc) · 2.52 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
99
100
101
package class01;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
/**
* @author pacai
* @version 1.0
*/
@SuppressWarnings("all")
public class MyHeap<T> {
private ArrayList<T> heap;
private HashMap<T, Integer> indexMap;
private int heapSize;
private Comparator<? super T> comparator;
public MyHeap(Comparator<? super T> comparator) {
heap = new ArrayList<>();
indexMap = new HashMap<>();
heapSize = 0;
this.comparator = comparator;
}
public boolean isEmpty() {
return heapSize == 0;
}
public int size() {
return heapSize;
}
public void push(T item) {
heap.add(item);
indexMap.put(item, heapSize);
heapInsert(heapSize++);
}
public boolean contains(T item) {
return indexMap.containsKey(item);
}
public T pop() {
if (isEmpty()) {
throw new HeapIsEmptyException();
}
T ans = heap.get(0);
int end = heapSize - 1;
swap(0, end);
heap.remove(end);
indexMap.remove(ans);
heapify(0, --heapSize);
return ans;
}
public void reset(T item){
Integer i = indexMap.get(item);
heapInsert(i);
heapify(i, heapSize);
}
private void heapInsert(int index) {
while (comparator.compare(heap.get(index), heap.get((index - 1) / 2)) < 0) {
swap(index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
private void heapify(int index, int heapSize) {
int left = 2 * index + 1;
while(left < heapSize){
int largest = left + 1 < heapSize &&
comparator.compare(heap.get(left + 1), heap.get(left)) < 0
? left + 1 : left;
largest = comparator.compare(heap.get(largest), heap.get(index)) < 0 ? index : largest;
if(largest == index){
break;
}
swap(index, largest);
index = largest;
left = 2 * index + 1;
}
}
private void swap(int i, int j) {
T o1 = heap.get(i);
T o2 = heap.get(j);
heap.set(i, o2);
heap.set(j, o1);
indexMap.put(o1, j);
indexMap.put(o2, i);
}
static class HeapIsEmptyException extends RuntimeException {
public HeapIsEmptyException() {
super("Heap is empty");
}
}
}