-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinPriorityQueue.java
97 lines (70 loc) · 2.99 KB
/
MinPriorityQueue.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package DS;
import java.util.ArrayList;
public class MinPriorityQueue<V> {
private final ArrayList<HeapPair<V>> heapArray;
public MinPriorityQueue() {
heapArray = new ArrayList<>();
heapArray.add(null);
}
public int size() { return (heapArray.size() - 1); }
public boolean isEmpty() { return size() == 0; }
public void emptyException()throws HeapEmptyException{
if (isEmpty()) {
HeapEmptyException e = new HeapEmptyException();
throw e;
}
}
public V min() throws HeapEmptyException {
emptyException();
return heapArray.get(1).value;
}
public V removeMin() throws HeapEmptyException {
emptyException();
HeapPair<V> minPair = heapArray.get(1);
int lastIndex = heapArray.size() - 1;
heapArray.set(1, heapArray.get(lastIndex));
heapArray.remove(lastIndex);
int currentPosition = 1,
firstChildPosition = 2*currentPosition,
secondChildPosition = 2*currentPosition + 1;
while (firstChildPosition < heapArray.size()) {
HeapPair<V> current = heapArray.get(currentPosition),
firstChild = heapArray.get(firstChildPosition),
secondChild = null;
if (secondChildPosition < heapArray.size())
secondChild = heapArray.get(secondChildPosition);
int toBeSwappedWithIndex = -1;
if (firstChild.priority < current.priority)
toBeSwappedWithIndex = firstChildPosition;
if ((secondChild != null) && (secondChild.priority < current.priority)
&& (secondChild.priority < firstChild.priority))
toBeSwappedWithIndex = secondChildPosition;
if (toBeSwappedWithIndex != -1) {
HeapPair<V> temp = heapArray.get(currentPosition);
heapArray.set(currentPosition,heapArray.get(toBeSwappedWithIndex));
heapArray.set(toBeSwappedWithIndex,temp);
}
else break;
currentPosition = toBeSwappedWithIndex;
firstChildPosition = currentPosition * 2;
secondChildPosition = currentPosition*2 + 1;
}
return minPair.value;
}
public void insert(int priority, V value) {
HeapPair<V> p = new HeapPair<>(priority, value);
heapArray.add(p);
int childIndex = heapArray.size() - 1,
parentIndex = childIndex/2;
while (childIndex > 1) {
if (heapArray.get(parentIndex).priority > heapArray.get(childIndex).priority) {
HeapPair<V> temp = heapArray.get(parentIndex);
heapArray.set(parentIndex,heapArray.get(childIndex));
heapArray.set(childIndex,temp);
}
else break;
childIndex = parentIndex;
parentIndex /= 2;
}
}
}