-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeRemoveMin.java
More file actions
94 lines (77 loc) · 2.64 KB
/
CodeRemoveMin.java
File metadata and controls
94 lines (77 loc) · 2.64 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
// Code : Remove Min
// Send Feedback
// Implement the function RemoveMin for the min priority queue class.
// For a minimum priority queue, write the function for removing the minimum
// element present. Remove and return the minimum element.
// Note : main function is given for your reference which we are using
// internally to test the code.
import java.util.ArrayList;
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 {
// Complete this function
if (heap.size() == 0) {
throw new PriorityQueueException();
}
int removed = heap.get(0);
heap.set(0, heap.get(size() - 1));
heap.remove(heap.size() - 1);
int parentIndex = 0;
int leftChildIndex = 2 * parentIndex + 1;
int rightChildIndex = 2 * parentIndex + 2;
while (leftChildIndex < heap.size()) {
int minIndex = parentIndex;
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;
}
int temp = heap.get(minIndex);
heap.set(minIndex, heap.get(parentIndex));
heap.set(parentIndex, temp);
parentIndex = minIndex;
leftChildIndex = 2 * parentIndex + 1;
rightChildIndex = 2 * parentIndex + 2;
}
return removed;
// Throw the exception PriorityQueueException if queue is empty
}
}
class PriorityQueueException extends Exception {
}