forked from AdaGold/heaps
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmin_heap.rb
More file actions
95 lines (74 loc) · 1.6 KB
/
min_heap.rb
File metadata and controls
95 lines (74 loc) · 1.6 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class HeapNode
attr_reader :key, :value
def initialize(key, value)
@key = key
@value = value
end
end
class MinHeap
def initialize
@store = []
end
# Time Complexity: ? O(log n)
# Space Complexity: ? O(nm)
def add(key, value = key)
node = HeapNode.new(key, value)
@store << node
heap_up(@store.length - 1)
end
# Time Complexity: O(log n)
# Space Complexity: Already have all the space we need.
def remove()
return nil if !@store
swap(0, @store.length - 1)
nope = @store.pop
heap_down(0)
return nope.value
end
# Used for Testing
def to_s
return "[]" if @store.empty?
output = "["
(@store.length - 1).times do |index|
output += @store[index].value + ", "
end
output += @store.last.value + "]"
return output
end
# Time complexity: Exceedingly fast.
# Space complexity: Literally one bit.
def empty?
!@store
end
private
# Time complexity: O(log n)
# Space complexity: O(nm)
def heap_up(i)
return if i == 0
pnode = (i-1) / 2
if @store[i].key < @store[pnode].key
swap(i, pnode)
heap_up(pnode)
end
end
def heap_down(i)
li = i*2+1
ri = i*2+2
if ri < @store.length
min = @store[li].key < @store[ri].key ? li : ri
if @store[i].key > @store[min].key
swap(i, min)
heap_down(min)
end
elsif li < @store.length
if @store[i].key > @store[li].key
swap(i, li)
end
end
end
def swap(index_1, index_2)
temp = @store[index_1]
@store[index_1] = @store[index_2]
@store[index_2] = temp
end
end