Class Containers::MaxHeap

  1. lib/containers/heap.rb

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 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 416
416:   def initialize(ary=[])
417:     super(ary) { |x, y| (x <=> y) == 1 }
418:   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 428
428:   def max
429:     self.next
430:   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 441
441:   def max!
442:     self.pop
443:   end