Class Containers::MinHeap

  1. lib/containers/heap.rb

A MinHeap is a heap where the items are returned in ascending order of key value.

Methods

public class

  1. new

public instance

  1. min
  2. min!

Public class methods

MinHeap.new(ary) → new_heap

Creates a new MinHeap with an optional array parameter of items to insert into the heap. A MinHeap is created by calling Heap.new { |x, y| (x <=> y) == -1 }, so this is a convenience class.

minheap = MinHeap.new([1, 2, 3, 4])
minheap.pop #=> 1
minheap.pop #=> 2
[show source]
     # File lib/containers/heap.rb, line 458
458:   def initialize(ary=[])
459:     super(ary) { |x, y| (x <=> y) == -1 }
460:   end

Public instance methods

min → value
min → nil

Returns the item with the smallest key, but does not remove it from the heap.

minheap = MinHeap.new([1, 2, 3, 4])
minheap.min #=> 1
[show source]
     # File lib/containers/heap.rb, line 470
470:   def min
471:     self.next
472:   end
min! → value
min! → nil

Returns the item with the smallest key and removes it from the heap.

minheap = MinHeap.new([1, 2, 3, 4])
minheap.min! #=> 1
minheap.size #=> 3
[show source]
     # File lib/containers/heap.rb, line 483
483:   def min!
484:     self.pop
485:   end