Class: Heap::BinaryHeap::MinHeap
- Inherits:
-
Object
- Object
- Heap::BinaryHeap::MinHeap
- Defined in:
- lib/Heap/binary_heap/binary_heap_min.rb
Instance Attribute Summary collapse
-
#elements ⇒ Object
readonly
Returns the value of attribute elements.
Instance Method Summary collapse
- #add(element) ⇒ Object
- #count ⇒ Object
- #extract_min ⇒ Object
- #extract_min! ⇒ Object
-
#initialize(elements = []) ⇒ MinHeap
constructor
A new instance of MinHeap.
- #sort ⇒ Object
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
#elements ⇒ Object (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 |
#count ⇒ Object
16 17 18 |
# File 'lib/Heap/binary_heap/binary_heap_min.rb', line 16 def count @elements.length end |
#extract_min ⇒ Object
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 |
#sort ⇒ Object
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 |