Skip to content

Instantly share code, notes, and snippets.

@ramkumar-kr
Created December 19, 2019 05:47
Show Gist options
  • Save ramkumar-kr/f002d6b154df4571ab31b96fdfefc4c5 to your computer and use it in GitHub Desktop.
Save ramkumar-kr/f002d6b154df4571ab31b96fdfefc4c5 to your computer and use it in GitHub Desktop.
Very simple heap implementation in ruby
class MinHeap
attr_reader :heap
def initialize()
@heap = []
end
def insert(element)
@heap.push(element)
heapify_up(@heap.size - 1)
end
def extract_min
element = @heap[0]
@heap[0] = @heap.pop
heapify_down(0)
element
end
private
def heapify_up(num)
return if num <= 0
parent = (num - 1) / 2
if @heap[num] < @heap[parent]
temp = @heap[num]
@heap[num] = @heap[parent]
@heap[parent] = temp
end
heapify_up(parent)
end
def heapify_down(num)
return if num > (@heap.size - 1)
left_child = num * 2 + 1
right_child = num * 2 + 2
return if left_child > (@heap.size - 1)
if right_child > (@heap.size - 1)
if @heap[num] > @heap[left_child]
@heap[num], @heap[left_child] = @heap[left_child], @heap[num]
end
return
end
return if @heap[num] <= @heap[left_child] && @heap[num] <= @heap[right_child]
if @heap[num] > @heap[right_child] && @heap[right_child] <= @heap[left_child]
@heap[num], @heap[right_child] = @heap[right_child], @heap[num]
heapify_down(right_child)
elsif @heap[num] > @heap[left_child] && @heap[left_child] <= @heap[right_child]
@heap[num], @heap[left_child] = @heap[left_child], @heap[num]
heapify_down(left_child)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment