This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Priority_Queue.js
87 lines (78 loc) · 2.12 KB
/
Priority_Queue.js
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
class queueElement {
constructor(element, priority) {
this.element = element;
this.prioriry = priority;
}
}
class PriorityQueue {
constructor() {
this.items = [];
}
//to add an element to the queue
enqueue(element, priority) {
var newQueueElement = new queueElement(element, priority);
var isPresent = false;
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].priority > newQueueElement.priority) {
this.items.splice(i, 0, newQueueElement);
isPresent = true;
break;
}
}
if (!isPresent) {
this.items.push(newQueueElement);
}
}
//to remove element form a queue
dequeue() {
if (this.isEmpty()) {
return "Underflow";
}
return this.items.shift();
}
//the front function
//returns the highest priority elemnt of queue
front() {
if (this.isEmpty()) {
return "Empty Queue";
}
return this.items[0];
}
//the rear function
// returns the lowest priorty element of the queue
rear() {
if (this.isEmpty()) {
return "Empty Queue";
}
return this.items[this.items.length - 1];
}
// isEmpty function
isEmpty() {
return this.items.length == 0; //true if queue is empty
}
// printQueue function
printPriorityQueue() {
var string = "";
for (var i = 0; i < this.items.length; i++)
string += this.items[i].element + " ";
return string;
}
}
var newPriorityQueue = new PriorityQueue();
newPriorityQueue.enqueue("1", 1);
newPriorityQueue.enqueue("2", 2);
newPriorityQueue.enqueue("3", 3);
newPriorityQueue.enqueue("4", 4);
newPriorityQueue.enqueue("5", 5);
console.log(newPriorityQueue.printPriorityQueue());
console.log(newPriorityQueue.front().element);
console.log(newPriorityQueue.rear().element);
console.log(newPriorityQueue.dequeue().element);
//After dequeue
console.log(newPriorityQueue.printPriorityQueue());
//OUTPUT =>
// 1 2 3 4 5
// 1
// 5
// 1
// 2 3 4 5