Class: BinaryHeap::Base

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/binary_heap/base.rb

Instance Method Summary collapse

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

#clearObject



59
60
61
62
# File 'lib/binary_heap/base.rb', line 59

def clear
  @heap.clear
  self
end

#eachObject



19
20
21
# File 'lib/binary_heap/base.rb', line 19

def each
  @heap.each
end

#lengthObject



15
16
17
# File 'lib/binary_heap/base.rb', line 15

def length
  @heap.length
end

#minObject



50
51
52
# File 'lib/binary_heap/base.rb', line 50

def min
  @heap[0]
end

#popObject



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