-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriority_queue.rb
53 lines (40 loc) · 1.11 KB
/
priority_queue.rb
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
class PriorityQueue
# The entries in @elements must
# respond to the <=>
attr_reader :elements
def initialize
@elements = [nil]
end
def <<(element)
@elements << element
bubble_up(@elements.size - 1)
end
def pop
exchange(1, @elements.size - 1)
max = @elements.pop
bubble_down(1)
max
end
private
def bubble_up(index)
parent_index = (index / 2)
return if index <= 1
return if @elements[parent_index] >= @elements[index]
exchange(index, parent_index)
bubble_up(parent_index)
end
def bubble_down(index)
child_index = (index * 2)
return if child_index > @elements.size - 1
not_the_last_element = child_index < @elements.size - 1
left_element = @elements[child_index]
right_element = @elements[child_index + 1]
child_index += 1 if not_the_last_element && right_element > left_element
return if @elements[index] >= @elements[child_index]
exchange(index, child_index)
bubble_down(child_index)
end
def exchange(source, target)
@elements[source], @elements[target] = @elements[target], @elements[source]
end
end