Class: DataStructures101::Heap
- Inherits:
-
Object
- Object
- DataStructures101::Heap
- Defined in:
- lib/data_structures_101/heap.rb
Overview
Heap implementation
Instance Method Summary collapse
- #[](i) ⇒ Object
-
#initialize(*args, min_heap: false) ⇒ Heap
constructor
A new instance of Heap.
- #left(i) ⇒ Object
- #parent(i) ⇒ Object
- #right(i) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(*args, min_heap: false) ⇒ Heap
Returns a new instance of Heap.
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/data_structures_101/heap.rb', line 9 def initialize(*args, min_heap: false) @data = args @heap_check = ->(i, j) { return @data[i] >= @data[j] } if min_heap @heap_check = ->(i, j) { return @data[i] <= @data[j] } end build_heap end |
Instance Method Details
#[](i) ⇒ Object
24 25 26 |
# File 'lib/data_structures_101/heap.rb', line 24 def [](i) @data[i] end |
#left(i) ⇒ Object
28 29 30 |
# File 'lib/data_structures_101/heap.rb', line 28 def left(i) 2 * i + 1 end |
#parent(i) ⇒ Object
36 37 38 |
# File 'lib/data_structures_101/heap.rb', line 36 def parent(i) (i - 1) / 2 end |
#right(i) ⇒ Object
32 33 34 |
# File 'lib/data_structures_101/heap.rb', line 32 def right(i) 2 * (i + 1) end |
#size ⇒ Object
20 21 22 |
# File 'lib/data_structures_101/heap.rb', line 20 def size @data.size end |