Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Priority Queue

/*PriorityQueue is an abstract data type that can be implemented in many different ways*/
class PriorityQueue{
    constructor()
    {
    this.items   = []        
    }
  
  
  enqueue(element, priority)
{
var qElement = new QElement(element, priority);
var contains = false;

/*check if element already in the items array*/
/*then check what position the element should be added*/
/*when an element is higher priority, add new element one position behind it*/
for (var i=0; i<this.items.length; i++)
{
if(this.items[i].priority > qElement.priority)
{
this.items.splice(i, 0, qElement);
contains = true;
break
}
}

if(!contains)
  {
this.items.push(qElement);
    }
  
  
}/*enqueue*/

  dequeue()
{
if(this.isEmpty())
{
return “Underflow”
}
return this.items.shift();

}
  
  front()
{

if (this.isEmpty())

return “No elements in Queue”;

return this.items[0];

}
  
  isEmpty()
  {
  return this.items == 0;
  }
  
  printPQueue()
{
  var str = "";
  for(var i =0; i<this.items.length; i++)
  {
    str += this.items[i].element + " ";
  }
  return str;
  

  
}
  
}

 
PREVIOUS NEXT
Tagged: #Priority #Queue
ADD COMMENT
Topic
Name
8+2 =