priorityQueue.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * The PriorityQeueu class
  3. */
  4. var PriorityQueue = function(comparator){
  5. this.init(comparator);
  6. }
  7. var pro = PriorityQueue.prototype;
  8. pro.init = function(comparator){
  9. this._comparator = typeof(comparator)=='function'?comparator:this._defaultComparator;
  10. this._queue = [];
  11. this._tailPos = 0;
  12. }
  13. /**
  14. * Return the size of the pirority queue
  15. * @return PirorityQueue size
  16. */
  17. pro.size = function(){
  18. return this._tailPos;
  19. };
  20. /**
  21. * Insert an element to the queue
  22. * @param element The element to insert
  23. */
  24. pro.offer = function(element){
  25. var queue = this._queue;
  26. var compare = this._comparator;
  27. queue[this._tailPos++] = element;
  28. var pos = this._tailPos-1;
  29. while(pos > 0){
  30. var parentPos = (pos%2==0)?(pos/2-1):(pos-1)/2;
  31. if(compare(queue[parentPos], element)){
  32. queue[pos] = queue[parentPos];
  33. queue[parentPos] = element;
  34. pos = parentPos;
  35. }else{
  36. break;
  37. }
  38. }
  39. };
  40. /**
  41. * Get and remove the first element in the queue
  42. * @return The first element
  43. */
  44. pro.pop = function(){
  45. var queue = this._queue;
  46. var compare = this._comparator;
  47. if(this._tailPos == 0)
  48. return null;
  49. var headNode = queue[0];
  50. var tail = queue[this._tailPos - 1];
  51. var pos = 0;
  52. var left = pos*2 + 1;
  53. var right = left + 1;
  54. queue[pos] = tail;
  55. this._tailPos--;
  56. while(left < this._tailPos){
  57. if(right<this._tailPos && compare(queue[left], queue[right]) && compare(queue[pos], queue[right])){
  58. queue[pos] = queue[right];
  59. queue[right] = tail;
  60. pos = right;
  61. }else if(compare(queue[pos],queue[left])){
  62. queue[pos] = queue[left];
  63. queue[left] = tail;
  64. pos = left;
  65. }else{
  66. break;
  67. }
  68. left = pos*2 + 1;
  69. right = left + 1;
  70. }
  71. return headNode;
  72. };
  73. /**
  74. * Get but not remove the first element in the queue
  75. * @return The first element
  76. */
  77. pro.peek = function(){
  78. if(this._tailPos == 0)
  79. return null;
  80. return this._queue[0];
  81. }
  82. pro._defaultComparator = function(a , b){
  83. return a > b;
  84. }
  85. module.exports.createPriorityQueue = function(comparator){
  86. return new PriorityQueue(comparator);
  87. }