-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathPriorityQueue.java
157 lines (129 loc) · 3.47 KB
/
PriorityQueue.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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
Solved By: Sandeep Ranjan (1641012352)
Solution for Programming Project
4.4
*/
class PQueue {
private int[] a;
private int max;
private int rear;
private int front;
//Considering smallest number to have maximum priority
public PQueue(int max) {
this.max = max;
a = new int[max];
rear = front = -1;
}
public boolean isFull() {
if(rear == max -1) return true;
else return false;
}
public boolean isEmpty() {
if(rear == -1 ) return true;
else return false;
}
public void display() {
int i;
if(!isEmpty()) {
for(i=front;i<=rear;i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
else {
System.out.println("Queue is Empty");
}
}
//(Insert Slow and Delete Fast)
public void insert(int val) {
if(isFull()) {
System.out.println("Overflow as queue is Full");
} else {
if(isEmpty()) {
front = rear = 0;
a[rear] = val;
} else {
int j;
for(j=rear; j>=0; j--) {
if(val > a[j]) {
a[j+1] = a[j];
} else {
break;
}
}
a[j+1] = val;
rear++;
System.out.println(val + " Added");
}
}
}
public int delete() {
if(isEmpty()) {
System.out.println("Underflow as Queue is Empty");
return -1;
} else {
int ele = a[rear];
if(front == rear) {
front = rear = -1;
} else {
rear--;
}
return ele;
}
}
// Project 4.4 (Insert Fast and Delete Slow)
// public void insert(int val) {
// if(isFull()) {
// System.out.println("Overflow");
// } else {
// if(isEmpty()) {
// front = rear = 0;
// a[rear] = val;
// } else {
// rear++;
// a[rear] = val;
// }
// }
// }
// public int delete() {
// if(!isEmpty()) {
// if(rear == front) {
// int ele = a[rear];
// rear = front = -1;
// return ele;
// } else { //find minimum
// int pos = 0;
// int min = a[0];
// for(int i=0; i<=rear; i++) {
// if(a[i]<min) {
// min = a[i];
// pos = i;
// }
// }
// for(int i=pos; i<rear; i++) {
// a[i] = a[i+1];
// }
// max--;
// rear--;
// return min;
// }
// } else {
// System.out.println("Underflow");
// }
// return -1;
// }
//------------------------------------
}
class PriorityQueue {
public static void main(String arg[]) {
PQueue pQ=new PQueue(5);
pQ.insert(10);
pQ.insert(80);
pQ.insert(20);
pQ.insert(50);
pQ.display();
while(!pQ.isEmpty()) {
System.out.print( pQ.delete() + " " );
}
}
}