Method: Containers::Heap#merge!

Defined in:
lib/containers/heap.rb

#merge!(otherheap) ⇒ Object

call-seq:

merge!(otherheap) -> merged_heap

Does a shallow merge of all the nodes in the other heap.

Complexity: O(1)

heap = MinHeap.new([5, 6, 7, 8])
otherheap = MinHeap.new([1, 2, 3, 4])
heap.merge!(otherheap)
heap.size #=> 8
heap.pop #=> 1

Raises:

  • (ArgumentError)


170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/containers/heap.rb', line 170

def merge!(otherheap)
  raise ArgumentError, "Trying to merge a heap with something not a heap" unless otherheap.kind_of? Containers::Heap
  other_root = otherheap.instance_variable_get("@next")
  if other_root
    @stored = @stored.merge(otherheap.instance_variable_get("@stored")) { |key, a, b| (a << b).flatten }
    # Insert othernode's @next node to the left of current @next
    @next.left.right = other_root
    ol = other_root.left
    other_root.left = @next.left
    ol.right = @next
    @next.left = ol
    
    @next = other_root if @compare_fn[other_root.key, @next.key]
  end
  @size += otherheap.size
end