Add elements to a PriorityQueue using Javascript


Enqueuing elements to a PriorityQueue means adding them in the array in order of the priority of the element. We'll consider higher numbers to be higher priorities. We'll loop through the container till we find a lower priority and then add the element there. If not, then we'll push it at the end of the container.

Note that we're creating the element object with the data and priority. Hence we can implement the enqueue function as follows −  

Example

enqueue(data, priority) {
   // Check if Queue is full
   if (this.isFull()) {
      console.log("Queue Overflow!");
      return;
   }
   let currElem = new this.Element(data, priority);
   let addedFlag = false;
   // Since we want to add elements to end, we'll just push them.
   for(let i = 0; i < this.container.length; i ++) {
       if(currElem.priority < this.container[i].priority) {
          this.container.splice(i, 0, currElem);
         addedFlag = true; break;
      }
   }
   if (!addedFlag) {
      this.container.push(currElem);
   }
}

You can check if this function is working fine using − 

Example

let q = new PriorityQueue(4);
q.enqueue("Hello", 3);
q.enqueue("World", 2);
q.enqueue("Foo", 8);
q.display();

Output

This will give the output −

[ { data: 'World', priority: 2 },
  { data: 'Hello', priority: 3 },
  { data: 'Foo', priority: 8 } ]

As you can see the elements are in a sorted order. The enqueue function works like insertion sort's insertions.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements