class Containers::MaxHeap

A MaxHeap is a heap where the items are returned in descending order of key value.

Public Class Methods

new(ary) → new_heap click to toggle source

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

maxheap = MaxHeap.new([1, 2, 3, 4])
maxheap.pop #=> 4
maxheap.pop #=> 3
Calls superclass method Containers::Heap.new
# File lib/containers/heap.rb, line 432
def initialize(ary=[])
  super(ary) { |x, y| (x <=> y) == 1 }
end

Public Instance Methods

max → value click to toggle source
max → nil

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

maxheap = MaxHeap.new([1, 2, 3, 4])
maxheap.max #=> 4
# File lib/containers/heap.rb, line 444
def max
  self.next
end
max! → value click to toggle source
max! → nil

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

maxheap = MaxHeap.new([1, 2, 3, 4])
maxheap.max! #=> 4
maxheap.size #=> 3
# File lib/containers/heap.rb, line 457
def max!
  self.pop
end