-
Notifications
You must be signed in to change notification settings - Fork 116
/
Priority Queues:Max Priority Queue
98 lines (93 loc) · 2.53 KB
/
Priority Queues:Max Priority Queue
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
import java.util.ArrayList;
/*************
* Following is the main function for your reference which we are using internally.
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
int choice = s.nextInt();
while(choice != -1) {
switch(choice) {
case 1 : // insert
int element = s.nextInt();
pq.insert(element);
break;
case 2 : // getMax
System.out.println(pq.getMax());
break;
case 3 : // removeMax
System.out.println(pq.removeMax());
break;
case 4 : // size
System.out.println(pq.getSize());
break;
case 5 : // isEmpty
System.out.println(pq.isEmpty());
default :
return;
}
choice = s.nextInt();
}
}
************/
public class PriorityQueue {
ArrayList<Integer> heap;
public PriorityQueue(){
heap=new ArrayList<>();
}
int getSize(){
return heap.size();
}
boolean isEmpty(){
return heap.size()==0;
}
int getMax(){
if(isEmpty())
return Integer.MIN_VALUE;
return heap.get(0);
}
void insert(int element){
heap.add(element);
int childindex=heap.size()-1;
int parentindex=(childindex-1)/2;
//upheapify------
while(childindex>0){
if(heap.get(childindex)>heap.get(parentindex))
{
int temp=heap.get(parentindex);
heap.set(parentindex,heap.get(childindex));
heap.set(childindex,temp);
childindex=parentindex;
parentindex=(childindex-1)/2;
}
else
return;
}
}
int removeMax(){
if(isEmpty())
return Integer.MIN_VALUE;
int lchildindex=1;
int rchildindex=2;
int parentindex=0;
int maxindex=parentindex;
int temp=heap.get(0);
heap.set(0,heap.get(heap.size()-1));
heap.remove(heap.size()-1);
while(lchildindex<heap.size()){
if(heap.get(lchildindex)>heap.get(parentindex))
maxindex=lchildindex;
if(rchildindex<heap.size() && heap.get(rchildindex)>heap.get(maxindex))
maxindex=rchildindex;
if(maxindex==parentindex)
break;
else{
int temp1=heap.get(parentindex);
heap.set(parentindex,heap.get(maxindex));
heap.set(maxindex,temp1);
parentindex=maxindex;
lchildindex=2*parentindex +1;
rchildindex=2*parentindex +2;
}
}
return temp;
}
}