-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathmin_priority_queue.rb
More file actions
95 lines (90 loc) · 2.52 KB
/
Copy pathmin_priority_queue.rb
File metadata and controls
95 lines (90 loc) · 2.52 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
require_relative './min_heap'
require_relative './monkey_patch'
using MonkeyPatch
module Heap
module MinPriorityQueue
class << self
# Public: Returns the minimum 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_min_heap(arr)
# heap_minimum(arr)
# => 1
def heap_minimum(arr)
arr[0]
end
# Public: Returns the minimum 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_min_heap(arr)
# heap_extract_min(arr)
# => 1
def heap_extract_min(arr)
arr.heap_size ||= arr.length
# raise 'heap underflow' if arr.heap_size < 1
return nil if arr.heap_size < 1
min = arr[0]
arr[0] = arr[arr.heap_size - 1]
arr.heap_size -= 1
Heap::MinHeap::min_heapify(arr, 0)
min
end
# Public: Decreases 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_decrease_key(arr, 8, 0)
#
# Modifies the input array
def heap_decrease_key(arr, i, key)
raise 'new key is bigger 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]
# min_heap_insert(arr, 0)
#
# Modifies the input array
def min_heap_insert(arr, key)
arr.heap_size ||= arr.length
arr.heap_size += 1
arr[arr.heap_size-1] = -Float::INFINITY
heap_decrease_key(arr, arr.heap_size-1, key)
end
end
end
end