Class: DataStructures101::Heap

Inherits:
Object
  • Object
show all
Defined in:
lib/data_structures_101/heap.rb

Overview

Heap implementation

Author:

  • Rene Hernandez

Since:

  • 0.3

Instance Method Summary collapse

Constructor Details

#initialize(*args, min_heap: false) ⇒ Heap

Returns a new instance of Heap.

Since:

  • 0.3



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

Since:

  • 0.3



24
25
26
# File 'lib/data_structures_101/heap.rb', line 24

def [](i)
  @data[i]
end

#left(i) ⇒ Object

Since:

  • 0.3



28
29
30
# File 'lib/data_structures_101/heap.rb', line 28

def left(i)
  2 * i + 1
end

#parent(i) ⇒ Object

Since:

  • 0.3



36
37
38
# File 'lib/data_structures_101/heap.rb', line 36

def parent(i)
  (i - 1) / 2
end

#right(i) ⇒ Object

Since:

  • 0.3



32
33
34
# File 'lib/data_structures_101/heap.rb', line 32

def right(i)
  2 * (i + 1)
end

#sizeObject

Since:

  • 0.3



20
21
22
# File 'lib/data_structures_101/heap.rb', line 20

def size
  @data.size
end