-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathmax_priority_queue.rb
96 lines (91 loc) · 2.58 KB
/
max_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
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
96
require_relative './max_heap'
require_relative './monkey_patch'
using MonkeyPatch
module Heap
module MaxPriorityQueue
class << self
# Public: Returns the maximium element in the heap, which is the element at
# index 0 after building the heap structure
#
# ARGS:
# arr - Input array
#
# Return: Integer
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# build_max_heap(arr)
# heap_maximum(arr)
# => 9
def heap_maximum(arr)
arr[0]
end
# Public: Returns the maximium element in the heap, which is the element at
# index 0 after building the heap structure
#
# ARGS:
# arr - Input array
#
# Return: Integer
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# build_max_heap(arr)
# heap_extract_max(arr)
# => 9
def heap_extract_max(arr)
arr.heap_size ||= arr.length
raise 'heap underflow' if arr.heap_size < 1
max = arr[0]
arr[0] = arr[arr.heap_size - 1]
arr.heap_size -= 1
Heap::MaxHeap::max_heapify(arr, 0)
max
end
# Public: Increases the element at the specified position to the value provided
# and makes sure the max-heap property holds
#
# ARGS:
# arr - Input array
# i - Index at which the element has to be increased
# key - New value of the index location
#
# Return: nil
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# heap_increase_key(arr, 3, 10)
# arr = [10, 5, 8, 3, 9, 6, 2, 4, 1]
#
# Modifies the input array
def heap_increase_key(arr, i, key)
raise 'new key is smaller than current key' if key < arr[i]
arr[i] = key
while i > 0 && arr[i.parent] < arr[i]
arr[i], arr[i.parent] = arr[i.parent], arr[i]
i = i.parent
end
end
# Public: Inserts an element into the array by maintaining the heap property
#
# ARGS:
# arr - Input array
# key - value to be inserted into the array
#
# Return: nil
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# max_heap_insert(arr, 10)
# arr = [10, 5, 3, 7, 8, 6, 2, 4, 1, 9]
#
# Modifies the input array
def max_heap_insert(arr, key)
arr.heap_size ||= arr.length
arr.heap_size += 1
arr[arr.heap_size-1] = -Float::INFINITY
heap_increase_key(arr, arr.heap_size-1, key)
end
end
end
end