Class: RubyCollections::MaxHeap
- Inherits:
-
Object
- Object
- RubyCollections::MaxHeap
- Defined in:
- lib/ruby_collections/max_heap.rb
Instance Attribute Summary collapse
-
#heap ⇒ Object
readonly
Returns the value of attribute heap.
Instance Method Summary collapse
- #extract_max ⇒ Object
-
#initialize(arr = []) ⇒ MaxHeap
constructor
A new instance of MaxHeap.
- #insert(val) ⇒ Object
- #max ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(arr = []) ⇒ MaxHeap
Returns a new instance of MaxHeap.
4 5 6 7 8 9 |
# File 'lib/ruby_collections/max_heap.rb', line 4 def initialize(arr = []) @heap = arr.unshift(nil) (@heap.length/2).downto(1) do |i| heapify(i) end end |
Instance Attribute Details
#heap ⇒ Object (readonly)
Returns the value of attribute heap.
3 4 5 |
# File 'lib/ruby_collections/max_heap.rb', line 3 def heap @heap end |
Instance Method Details
#extract_max ⇒ Object
11 12 13 14 15 16 17 18 |
# File 'lib/ruby_collections/max_heap.rb', line 11 def extract_max max, length = heap[1], heap.length heap[1] = nil swap(1, length-1) heapify(1) heap.pop return max end |
#insert(val) ⇒ Object
28 29 30 31 32 33 34 35 |
# File 'lib/ruby_collections/max_heap.rb', line 28 def insert(val) heap[heap.length], parent, current = val, parent(heap.length), heap.length until heap[parent] >= val swap(current, parent) current = parent parent = parent(parent) end end |
#max ⇒ Object
20 21 22 |
# File 'lib/ruby_collections/max_heap.rb', line 20 def max heap[1] end |
#size ⇒ Object
24 25 26 |
# File 'lib/ruby_collections/max_heap.rb', line 24 def size @heap.length-1 end |