class Containers::MaxHeap

  1. lib/containers/heap.rb
Parent: Containers

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

Methods

Public Class

  1. new

Public Instance

  1. max
  2. max!

Public Class methods

MaxHeap.new(ary) -> new_heap

Creates a new MaxHeap with an optional array parameter of items to insert into the heap. A MaxHeap is created by calling Containers::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
[show source]
# File lib/containers/heap.rb, line 432
def initialize(ary=[])
  super(ary) { |x, y| (x <=> y) == 1 }
end

Public Instance methods

max -> value
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
[show source]
# File lib/containers/heap.rb, line 444
def max
  self.next
end
max! -> value
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
[show source]
# File lib/containers/heap.rb, line 457
def max!
  self.pop
end