Advertisement
Guest User

Untitled

a guest
May 24th, 2015
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. var Heap = (function(){
  2. function otheri(index, level_offset){
  3. var level = Math.floor(Math.log2(index+1));
  4. var level_start = Math.pow(2, level) - 1;
  5. var offset = index - level_start;
  6. var other_level_start = Math.pow(2, level + level_offset) -1;
  7. var other_offset = Math.floor(offset * Math.pow(2, level_offset));
  8. return other_level_start + other_offset;
  9. };
  10.  
  11. function parenti(index){
  12. return otheri(index, -1);
  13. };
  14.  
  15. function childreni(index){
  16. return otheri(index, 1);
  17. };
  18.  
  19. function Heap(comparison){
  20. if(comparison){
  21. this.comparison = comparison;
  22. }
  23. this._data = []
  24. };
  25.  
  26. Heap.prototype.comparison = function(a, b){ return a >b;};
  27.  
  28. Heap.prototype.sift_up = function(index){
  29. var parent = parenti(index);
  30. if(parent < 0){
  31. return;
  32. }
  33.  
  34. if(! this.comparison(this._data[index], this._data[parent])){
  35. var temp = this._data[index];
  36. this._data[index] = this._data[parent];
  37. this._data[parent] = temp;
  38. if(index != 0){
  39. this.sift_up(parent);
  40. }
  41. }
  42. };
  43.  
  44. Heap.prototype.sift_down = function(index){
  45. var child_left_i = childreni(index);
  46. var child_right_i = child_left_i + 1;
  47. if(child_left_i >= this._data.length){
  48. return;
  49. }
  50. if(child_right_i > this._data.length){
  51. var smallest_child = child_left_i;
  52. var leaf = true;
  53. }
  54. else{
  55. var leaf = false;
  56. if(!this.comparison(this._data[child_left_i], this._data[child_right_i])){
  57. var smallest_child = child_left_i;
  58. }
  59. else{
  60. var smallest_child = child_right_i;
  61. }
  62. }
  63.  
  64. if(!this.comparison(this._data[smallest_child], this._data[index])){
  65. var temp = this._data[index];
  66. this._data[index] = this._data[smallest_child];
  67. this._data[smallest_child] = temp;
  68. this.sift_down(smallest_child);
  69. }
  70. };
  71.  
  72. Heap.prototype.push = function push(item){
  73. var new_index = this._data.length;
  74. this._data[new_index] = item;
  75. this.sift_up(new_index);
  76. return item;
  77. };
  78.  
  79. Heap.prototype.peek = function peek(){
  80. return this._data[0];
  81. }
  82.  
  83. Heap.prototype.pop = function pop(){
  84. var result = this._data[0];
  85. this._data[0] = this._data[this._data.length - 1];
  86. this.sift_down(0);
  87. this._data.pop()
  88. return result;
  89. };
  90.  
  91. return Heap;
  92. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement