Skip to content
Related Articles

Related Articles

Improve Article

Implementation of Priority Queue in Javascript

  • Difficulty Level : Medium
  • Last Updated : 22 Jul, 2021

Priority Queue is an extension of Queue having some properties as follows: 

  1. Each element of the priority queue has a priority associated with it.
  2. Elements are added to the queue as per the priority.
  3. Lowest priority elements are removed first.

We can design a priority queue using two approaches in the first case we can add the queue element at the end of the queue and we can remove the elements of the queue depending on the priority. In the second case, we can add elements to the queue according to the priority and remove them from the front of the queue. In this article, we would use the second approach to implement a Priority Queue. 

Note: Assuming a Priority queue can grow dynamically we are not considering the overflow condition. 

Let’s see an example of a priority queue class: 

Example:  



Javascript




// User defined class
// to store element and its priority
class QElement {
    constructor(element, priority)
    {
        this.element = element;
        this.priority = priority;
    }
}
 
// PriorityQueue class
class PriorityQueue {
 
    // An array is used to implement priority
    constructor()
    {
        this.items = [];
    }
 
    // functions to be implemented
    // enqueue(item, priority)
    // dequeue()
    // front()
    // isEmpty()
    // printPQueue()
}

As you can see in the example above we have defined the skeleton of PriorityQueue class. We have used a user defined class QElement having two property elements and priority. We have used an array in PriorityQueue class to implement the priority queue, this array is a container of QElement. 

1. enqueue() – adds an element to the queue according to its priority. 

Javascript




// enqueue function to add element
// to the queue as per priority
enqueue(element, priority)
{
    // creating object from queue element
    var qElement = new QElement(element, priority);
    var contain = false;
 
    // iterating through the entire
    // item array to add element at the
    // correct location of the Queue
    for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].priority > qElement.priority) {
            // Once the correct location is found it is
            // enqueued
            this.items.splice(i, 0, qElement);
            contain = true;
            break;
        }
    }
 
    // if the element have the highest priority
    // it is added at the end of the queue
    if (!contain) {
        this.items.push(qElement);
    }
}

In this method, we create a qElement have property element and priority. Then we iterate over the queue to find the correct location of the qElement according to its priority and add it.

2. dequeue() – Removes an element from the priority queue 

Javascript




// dequeue method to remove
// element from the queue
dequeue()
{
    // return the dequeued element
    // and remove it.
    // if the queue is empty
    // returns Underflow
    if (this.isEmpty())
        return "Underflow";
    return this.items.shift();
}

This function removes an element from the front of a queue as the highest priority element is stored at the front of the priority queue. We have used the shift method of an array to remove an element from the queue.



3. front() – returns the front element of the Priority queue 

Javascript




// front function
front()
{
    // returns the highest priority element
    // in the Priority queue without removing it.
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[0];
}

This function returns the front element of the Priority queue. We simply return the 0th element of an array to get the front of a Priority queue.

4. rear() – returns the last element of the Priority queue 

Javascript




// rear function
rear()
{
    // returns the lowest priority
    // element of the queue
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[this.items.length - 1];
}

This function returns the last element of the queue or lowest priority element.

Helper Methods: 
Let’s declare some helper method that is quite useful while working with the Priority queue.  

1. isEmpty() – Returns true if the Priority queue is empty

Javascript




// isEmpty function
isEmpty()
{
    // return true if the queue is empty.
    return this.items.length == 0;
}

We have used the length property of an array to get the length and if its 0 then priority queue is empty. 
 



2. printPQueue() – It prints the element of the queue as per the priority starting from highest to lowest 
 

Javascript




// printQueue function
// prints all the element of the queue
printPQueue()
{
    var str = "";
    for (var i = 0; i < this.items.length; i++)
        str += this.items[i].element + " ";
    return str;
}

In this method, we concatenate the element property of each priority queue item into a string.

Note:- Here we consider ” 1 ” as the highest priority element, you can modify this as per the requirement. 

Implementation 
Now Let use this Priority Queue class and its different method described above 

Javascript




// creating object for queue class
var priorityQueue = new PriorityQueue();
 
// testing isEmpty and front on an empty queue
// return true
console.log(priorityQueue.isEmpty());
 
// returns "No elements in Queue"
console.log(priorityQueue.front());
 
// adding elements to the queue
priorityQueue.enqueue("Sumit", 2);
priorityQueue.enqueue("Gourav", 1);
priorityQueue.enqueue("Piyush", 1);
priorityQueue.enqueue("Sunny", 2);
priorityQueue.enqueue("Sheru", 3);
 
// prints [Gourav Piyush Sumit Sunny Sheru]
console.log(priorityQueue.printPQueue());
 
// prints Gourav
console.log(priorityQueue.front().element);
 
// pritns Sheru
console.log(priorityQueue.rear().element);
 
// removes Gouurav
// priorityQueue contains
// [Piyush Sumit Sunny Sheru]
console.log(priorityQueue.dequeue().element);
 
// Adding another element to the queue
priorityQueue.enqueue("Sunil", 2);
 
// prints [Piyush Sumit Sunny Sunil Sheru]
console.log(priorityQueue.printPQueue());

This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :