-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathMinPriorityQueue.java
More file actions
81 lines (67 loc) · 1.89 KB
/
MinPriorityQueue.java
File metadata and controls
81 lines (67 loc) · 1.89 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
package priorityQueues;
import java.util.*;
public class MinPriorityQueue {
private ArrayList<Integer> heap;
public MinPriorityQueue() {
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;
//up-heapify
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() {
int minValue=heap.get(0);
int lastIndex=heap.size()-1;
heap.set(0,heap.get(lastIndex));
heap.remove(heap.size()-1);
//down-Heapify
int index=0;
int minIndex=index;
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==index){
break;
}
int temp=heap.get(index);
heap.set(index,heap.get(minIndex));
heap.set(minIndex,temp);
index=minIndex;
leftchildIndex=2*index+1;
rightchildIndex=2*index+2;
}
return minValue;
}
}