Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. class Heap
  2. def initialize(type = :min)
  3. @type = type
  4. if @type == :min
  5. @heap = [-1.0/0]
  6. @compare = ->(a,b) { (a <=> b) < 0 }
  7. elsif @type == :max
  8. @heap = [1.0/0]
  9. @compare = ->(a,b) { (b <=> a) > 0 }
  10. else
  11. raise "Unknown heap type"
  12. end
  13. @last = 0
  14. end
  15.  
  16. def push(value)
  17. @last += 1
  18. @heap[@last] = value
  19. bubble_up(@last)
  20. @last
  21. end
  22.  
  23. def peek
  24. @heap[1]
  25. end
  26.  
  27. def pop
  28. return nil if @last == 0
  29. value = @heap[1]
  30. @heap[1] = @heap[@last]
  31. @last -= 1
  32. bubble_down(1)
  33. value
  34. end
  35.  
  36. def size
  37. @last
  38. end
  39.  
  40. private
  41. def bubble_up(child)
  42. return if child == 1
  43. parent_index = parent(child)
  44. if @compare[@heap[child], @heap[parent_index]]
  45. @temp = @heap[child]
  46. @heap[child] = @heap[parent_index]
  47. @heap[parent_index] = @temp
  48. bubble_up(parent_index)
  49. end
  50. end
  51.  
  52. def bubble_down(parent_index)
  53. return if parent_index > parent(@last)
  54. left = left_child(parent_index)
  55. right = right_child(parent_index)
  56.  
  57. if right > @last
  58. child = left
  59. else
  60. child = @compare[@heap[left], @heap[right]] ? left : right
  61. end
  62.  
  63. if @compare[@heap[child], @heap[parent_index]]
  64. @temp = @heap[child]
  65. @heap[child] = @heap[parent_index]
  66. @heap[parent_index] = @temp
  67. bubble_down(child)
  68. end
  69.  
  70. end
  71.  
  72. def parent(index)
  73. index / 2
  74. end
  75.  
  76. def left_child(index)
  77. 2 * index
  78. end
  79.  
  80. def right_child(index)
  81. 2 * index + 1
  82. end
  83. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement