Priority Queue

In the following code on enqueing the element with same priority is added adjacent to each other how is it happening

function PriorityQueue () {
    var collection = [];
    this.printCollection = function() {
      (console.log(collection));
    };
    this.enqueue = function(element){
        if (this.isEmpty()){ 
            collection.push(element);
        } else {
            var added = false;
            for (var i=0; i<collection.length; i++){
                 if (element[1] < collection[i][1]){ //checking priorities
                    collection.splice(i,0,element);
                    added = true;
                    break;
                }
            }
            if (!added){
                collection.push(element);
            }
        }
    };
    this.dequeue = function() {
        var value = collection.shift();
        return value[0];
    };
    this.front = function() {
        return collection[0];
    };
    this.size = function() {
        return collection.length; 
    };
    this.isEmpty = function() {
        return (collection.length === 0); 
    };
}

var pq = new PriorityQueue(); 
pq.enqueue(['Beau Carnes', 2]); 
pq.enqueue(['Quincy Larson', 3]);
pq.enqueue(['Ewa Mitulska-WĂłjcik', 1])
pq.enqueue(['Briana Swift', 2])
pq.printCollection();
pq.dequeue();
console.log(pq.front());
pq.printCollection();

That’s the section with a “checking priorities” that does it.

Are you expecting something different to occur?

1 Like

if element to enque has a priority 1 and element in the collection has priority 1 at this point if condition has to fail right.

 if (element[1] < collection[i][1]){ //checking priorities
                    collection.splice(i,0,element);
                    added = true;
                    break;
                }

Yes, that’s right, because 1 is not less than 1.

plz explain me whats happening if we try to enque element with same priority and how it is adding adjacent to each other.

1 Like

What happens is that it looks through the queue from the the lowest priority values to the highest priority ones. When it finds a priority with a larger value than the one being adding, it squeezes the new one in before that one with the higher value.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.