Skip to content

Instantly share code, notes, and snippets.

@szolotykh
Last active August 29, 2015 13:55
Show Gist options
  • Save szolotykh/8761784 to your computer and use it in GitHub Desktop.
Save szolotykh/8761784 to your computer and use it in GitHub Desktop.
// Example: Priority Queue
var q = new PriorityQueue();
// Push
q.push('a',10);
q.push('b',1);
q.push('c',20);
q.push('d',5);
// Pop
console.log(q.pop());
// Priority Queue
function PriorityQueue(){
this.list = new Array()
this.push = function(el, priority){
this.list.push([el, priority]);
}
this.pop = function(){
if(this.list.length == 0)
return null;
var minPriority = this.list[0][1];
var minIndex = 0;
for(var i = 1; i < this.list.length; i++){
if(this.list[i][1] < minPriority){
minPriority = this.list[i][1];
minIndex = i;
}
}
var minValue = this.list[minIndex][0];
this.list.splice(minIndex, 1);
return minValue;
}
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment