-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.rb
More file actions
48 lines (35 loc) · 946 Bytes
/
heap.rb
File metadata and controls
48 lines (35 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Heap
private attr_reader :list
def initialize(list)
@list = list
end
def index_of_parent(index)
parent_index = (index - 1) / 2
return if parent_index.negative?
parent_index
end
def value_of_parent(index)
return if index_of_parent(index).nil?
@list[index_of_parent(index)]
end
def index_of_left_child(index)
left_child_index = (2 * index) + 1
return if left_child_index > list.length - 1
left_child_index
end
def value_of_left_child(index)
left_child_index = index_of_left_child(index)
return if left_child_index.nil?
list[left_child_index]
end
def index_of_right_child(index)
right_child_index = (2 * index) + 2
return if right_child_index > list.length - 1
right_child_index
end
def value_of_right_child(index)
right_child_index = index_of_right_child(index)
return if right_child_index.nil?
list[right_child_index]
end
end