Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. class Heap {
  2. constructor(sort) {
  3. this._array = [];
  4. if (!(sort instanceof Function))
  5. sort = (a, b) => b - a;
  6. this._sort = sort;
  7. Object.defineProperty(this, 'length', {
  8. enumerable: true,
  9. get: function() { return this._array.length },
  10. });
  11. }
  12.  
  13. push(node) {
  14. node = node || {};
  15. this._array.push(node);
  16. this._bubble();
  17. }
  18. pop() {
  19. if (this.isEmpty()) return null;
  20. let top = this.peek();
  21. let last = this._array.pop();
  22. if (this.length > 0) {
  23. this._array[0] = last;
  24. this._sink();
  25. }
  26. return top;
  27. }
  28. peek() {
  29. return this._array[0];
  30. }
  31. isEmpty() {
  32. return this.length === 0;
  33. }
  34.  
  35. _compare(i, j) {
  36. return this._sort(this._array[i], this._array[j]) > 0;
  37. }
  38. _bubble() {
  39. let i = this.length - 1;
  40. let j = this._parent(i);
  41. while (j !== null && this._compare(i, j)) {
  42. this._swap(i, j);
  43. i = j;
  44. j = this._parent(i);
  45. }
  46. }
  47. _sink() {
  48. let i = 0;
  49. let lc = this._left(i);
  50. let rc = this._right(i);
  51. let next;
  52.  
  53. while (lc !== null) {
  54. next = lc;
  55. if (rc !== null && this._compare(rc, lc))
  56. next = rc;
  57. if (this._compare(next, i)) {
  58. this._swap(i, next);
  59. i = next;
  60. lc = this._left(i);
  61. rc = this._right(i);
  62. }
  63. else return;
  64. }
  65. }
  66. print() {
  67. var s = '';
  68. var nodes = 1;
  69. var values = 0;
  70. for (var i = 0; i < this.length; i++) {
  71. s += ' ' + this._array[i].toString();
  72. values++;
  73. if (values === nodes) {
  74. nodes = nodes << 1;
  75. values = 0;
  76. s += '\n';
  77. }
  78. }
  79. console.log('\n' + s + '\n');
  80. };
  81. _parent(i) {
  82. let pi = (i - 1)/2 >> 0;
  83. return pi >= 0 ? pi : null;
  84. }
  85. _left(i) {
  86. let li = i*2 + 1;
  87. return li < this.length ? li : null;
  88. }
  89. _right(i) {
  90. let ri = i*2 + 2;
  91. return ri < this.length ? ri : null;
  92. }
  93. _swap(i, j) {
  94. var a = this._array;
  95. var v = a[i];
  96. a[i] = a[j];
  97. a[j] = v;
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement