Class: Heap::BinaryHeap::MinHeap

Inherits:
Object
  • Object
show all
Defined in:
lib/Heap/binary_heap/binary_heap_min.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(elements = []) ⇒ MinHeap

Returns a new instance of MinHeap.



6
7
8
9
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 6

def initialize(elements = [])
  @elements = []
  add(elements.pop) until elements.empty?
end

Instance Attribute Details

#elementsObject (readonly)

Returns the value of attribute elements.



4
5
6
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 4

def elements
  @elements
end

Instance Method Details

#add(element) ⇒ Object



11
12
13
14
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 11

def add(element)
  @elements.push element
  swim_up(count)
end

#countObject



16
17
18
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 16

def count
  @elements.length
end

#extract_minObject



20
21
22
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 20

def extract_min
  @elements[0]
end

#extract_min!Object



24
25
26
27
28
29
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 24

def extract_min!
  swap(1, count)
  el = @elements.pop
  swim_down(1)
  el
end

#sortObject



31
32
33
34
35
36
37
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 31

def sort
  el_temp = @elements.clone
  result = []
  result.push extract_min! while count > 0
  @elements = el_temp
  result
end