-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriority Queues:Remove Min
137 lines (108 loc) · 2.72 KB
/
Priority Queues:Remove Min
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import java.util.ArrayList;
/*****************
* Main function -
*
public static void main(String[] args) {
PQ pq = new PQ();
int choice = s.nextInt();
while(choice != -1) {
switch(choice) {
case 1 : // insert
int element = s.nextInt();
pq.insert(element);
break;
case 2 : // getMin
try {
System.out.println(pq.getMin());
} catch (PriorityQueueException e) {
return;
}
break;
case 3 : // removeMin
try {
System.out.println(pq.removeMin());
} catch (PriorityQueueException e) {
return;
}
break;
case 4 : // size
System.out.println(pq.size());
break;
case 5 : // isEmpty
System.out.println(pq.isEmpty());
default :
return;
}
choice = s.nextInt();
}
}
*******************/
class PriorityQueueException extends Exception {
}
public class PQ {
private ArrayList<Integer> heap;
public PQ() {
heap = new ArrayList<Integer>();
}
boolean isEmpty(){
return heap.size() == 0;
}
int size(){
return heap.size();
}
int getMin() throws PriorityQueueException{
if(isEmpty()){
// Throw an exception
throw new PriorityQueueException();
}
return heap.get(0);
}
void insert(int element){
heap.add(element);
int childIndex = heap.size() - 1;
int parentIndex = (childIndex - 1) / 2;
while(childIndex > 0){
if(heap.get(childIndex) < heap.get(parentIndex)){
int temp = heap.get(childIndex);
heap.set(childIndex, heap.get(parentIndex));
heap.set(parentIndex, temp);
childIndex = parentIndex;
parentIndex = (childIndex - 1) / 2;
}else{
return;
}
}
}
int removeMin() throws PriorityQueueException{
if(isEmpty()){
// Throw an exception
throw new PriorityQueueException();
}
int temp = heap.get(0);
heap.set(0, heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
int parentindex = 0;
int minIndex = parentindex;
int leftChildIndex = 1;
int rightChildIndex = 2;
while(leftChildIndex < heap.size()){
if(heap.get(leftChildIndex) < heap.get(minIndex)){
minIndex = leftChildIndex;
}
if(rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(minIndex)){
minIndex = rightChildIndex;
}
if(minIndex == parentindex){
break;
}else{
int temp1 = heap.get(parentindex);
heap.set(parentindex, heap.get(minIndex));
heap.set(minIndex, temp1);
parentindex = minIndex;
leftChildIndex = 2 * parentindex + 1;
rightChildIndex = 2 * parentindex + 2;
}
}
return temp;
}
}