Class: BinaryHeap::Base
- Inherits:
-
Object
- Object
- BinaryHeap::Base
- Includes:
- Enumerable
- Defined in:
- lib/binary_heap/base.rb
Instance Method Summary collapse
- #<<(el) ⇒ Object
- #clear ⇒ Object
- #each ⇒ Object
-
#initialize(ary = []) ⇒ Base
constructor
A new instance of Base.
- #length ⇒ Object
- #min ⇒ Object
- #pop ⇒ Object
- #push(*els) ⇒ Object
- #replace_min(el) ⇒ Object
Constructor Details
#initialize(ary = []) ⇒ Base
Returns a new instance of Base.
6 7 8 9 10 11 12 13 |
# File 'lib/binary_heap/base.rb', line 6 def initialize(ary=[]) if ary.is_a? Array @heap = ary.dup heapify else raise ArgumentError end end |
Instance Method Details
#<<(el) ⇒ Object
23 24 25 26 27 |
# File 'lib/binary_heap/base.rb', line 23 def <<(el) @heap << el rebalance_up(@heap.size - 1) self end |
#clear ⇒ Object
59 60 61 62 |
# File 'lib/binary_heap/base.rb', line 59 def clear @heap.clear self end |
#each ⇒ Object
19 20 21 |
# File 'lib/binary_heap/base.rb', line 19 def each @heap.each end |
#length ⇒ Object
15 16 17 |
# File 'lib/binary_heap/base.rb', line 15 def length @heap.length end |
#min ⇒ Object
50 51 52 |
# File 'lib/binary_heap/base.rb', line 50 def min @heap[0] end |
#pop ⇒ Object
41 42 43 44 45 46 47 48 |
# File 'lib/binary_heap/base.rb', line 41 def pop @heap[0], @heap[-1] = @heap[-1], @heap[0] res = @heap.pop if @heap.size.positive? rebalance_down(0) end res end |
#push(*els) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/binary_heap/base.rb', line 29 def push(*els) if els.length < length els.each do |el| self << el end else @heap.push(*els) heapify end self end |
#replace_min(el) ⇒ Object
54 55 56 57 |
# File 'lib/binary_heap/base.rb', line 54 def replace_min(el) @heap[0] = el rebalance_down(0) end |