-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathmin_heap.rb
57 lines (51 loc) · 1.35 KB
/
min_heap.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
require_relative './monkey_patch'
using MonkeyPatch
module Heap
module MinHeap
# Public: Ensures the min-heap property is being maintained from the index provided
# Recursive, Min-Heap property A[parent] <= A[left] as well as A[right]
#
# ARGS:
# arr - Input array
# i - Index at which the Min-Heap property is to be applied
#
# RETURN: nil
#
# COMPLEXITY: Θ(lgn)
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# min_heapify(arr, 5)
#
# Modifies the provided array.
def self.min_heapify(arr, i)
arr.heap_size ||= arr.length
l = i.left
r = i.right
smallest = (l <= arr.heap_size-1 && arr[l] < arr[i]) ? l : i
smallest = r if (r <= arr.heap_size-1 && arr[r] < arr[smallest])
if smallest != i
arr[i], arr[smallest] = arr[smallest], arr[i]
min_heapify(arr, smallest)
end
end
# Public: Re-order the input array to adhere to the Min-Heap property at all indices
#
# ARGS:
# arr - Input array
#
# RETURN: nil
#
# Examples
# arr = [5, 3, 8, 7, 9, 6, 2, 4, 1]
# build_min_heap(arr)
#
# Modifies the provided array.
def self.build_min_heap(arr)
arr.heap_size = arr.length
(0..arr.length.half).reverse_each do |i|
min_heapify(arr, i)
end
end
end
end