Guest User

Untitled

a guest
Jan 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. const PriorityQueue = function () {
  2. this.data = [];
  3. };
  4.  
  5. PriorityQueue.prototype.isEmpty = function() {
  6. return 0 === this.data.length;
  7. };
  8.  
  9. PriorityQueue.prototype.less = function(i, j) {
  10. return this.data[i] < this.data[j];
  11. };
  12.  
  13. PriorityQueue.prototype.swap = function (i, j) {
  14. let tmp = this.data[i];
  15. this.data[i] = this.data[j];
  16. this.data[j] = tmp;
  17. };
  18.  
  19. PriorityQueue.prototype.enqueue = function (...ele) {
  20. this.data.push(...ele);
  21. this.data.unshift(null);
  22. for (let i = parseInt((this.data.length - 1) / 2); i >= 1; i--) {
  23. if (this.less(i, i * 2)) this.swap(i, i * 2);
  24. if (this.data[i * 2 + 1] !== undefined && this.less(i, i * 2 + 1)) this.swap(i, i * 2 + 1);
  25. }
  26. this.data.shift();
  27. };
  28.  
  29. PriorityQueue.prototype.dequeue = function () {
  30. if (this.isEmpty()) return undefined;
  31.  
  32. const result = this.data.shift();
  33. this.data = [null, this.data[this.data.length - 1], ...this.data.slice(0, this.data.length - 1)];
  34. for (let i = 1; i <= parseInt((this.data.length - 1) / 2);) {
  35. let j = 2 * i;
  36. if (j < this.data.length - 1 && this.less(j, j + 1)) j++;
  37. if (!this.less(i, j)) break;
  38. this.swap(i, j);
  39. i = j;
  40. }
  41. this.data.shift();
  42. return result;
  43. };
  44.  
  45. const pq = new PriorityQueue();
  46. pq.enqueue(1, 13, 3);
  47. pq.enqueue(31, 3);
  48. pq.enqueue(22);
  49. console.log(pq.dequeue()); // 31
  50. console.log(pq.dequeue()); // 22
  51. console.log(pq.dequeue()); // 13
  52. console.log(pq.dequeue()); // 3
  53. console.log(pq.dequeue()); // 3
  54. console.log(pq.dequeue()); // 1
  55. console.log(pq.dequeue()); // undefined
Add Comment
Please, Sign In to add comment