-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriorityQueue.java
73 lines (63 loc) · 2.13 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
/*
* FILENAME : PriorityQueue.java
* Problem Statement:
* Implementation of Priority Queue using Heap
* ------------------------------------------------------------------------------
* AUTHOR : GANESH PAI, Dept. of CS&E, NMAMIT, Nitte
* YEAR : 2021
* E-mail : ganesh.pai@nitte.edu.in
* ------------------------------------------------------------------------------
*/
import java.util.Scanner;
public class PriorityQueue {
int heap[] = new int[50], noOfElements=0;
public void insert(int elem)
{
int i;
heap[++noOfElements] = elem;
for(i = noOfElements; (i > 1) && (heap[i/2] < elem); i /= 2)
heap[i] = heap[i/2];
heap[i] = elem;
}
public Integer remove()
{
if (noOfElements == 0)
return null;
int removedElem = heap[1];
heap[1] = heap[noOfElements--];
int j, elem = heap[1];
for(j = 2; j <= noOfElements; j = 2 * j)
{
if((j < noOfElements) && (heap[j] < heap[j+1]))
j++;
if(elem >= heap[j])
break;
heap[j / 2] = heap[j];
}
heap[j / 2] = elem;
return removedElem;
}
public static void main(String[] args) {
Scanner ip = new Scanner(System.in);
PriorityQueue hs = new PriorityQueue();
while(true)
{
System.out.println("Menu:\n1. Insert an element\n2.Remove an element\n3. Exit\nEnter your choice:");
switch(ip.nextInt())
{
case 1:
System.out.println("Enter a number: ");
hs.insert(ip.nextInt());
break;
case 2:
Integer elem = hs.remove();
if (elem == null)
System.out.println("Empty Queue");
else
System.out.println("Removed number is: " + elem);
break;
default:System.exit(0);
}
}
}
}