Skip to content

Instantly share code, notes, and snippets.

@flyptkarsh
Created March 8, 2024 16:16
Show Gist options
  • Select an option

  • Save flyptkarsh/7d09b95eb8594f38adc79c7cd6656e66 to your computer and use it in GitHub Desktop.

Select an option

Save flyptkarsh/7d09b95eb8594f38adc79c7cd6656e66 to your computer and use it in GitHub Desktop.
MaxHeap Ruby implementation
class MaxHeap
def initialize
@heap = []
end
def push(val)
@heap << val
sift_up(@heap.size - 1)
end
def pop
return @heap.pop if @heap.size <= 1
max = @heap.first
@heap[0] = @heap.pop
sift_down(0)
max
end
private
def sift_up(index)
return if index <= 0
parent_index = (index - 1) / 2
return if @heap[parent_index] >= @heap[index]
@heap[parent_index], @heap[index] = @heap[index], @heap[parent_index]
sift_up(parent_index)
end
def sift_down(index)
left_child_index = 2 * index + 1
right_child_index = 2 * index + 2
max_index = index
if left_child_index < @heap.size && @heap[left_child_index] > @heap[max_index]
max_index = left_child_index
end
if right_child_index < @heap.size && @heap[right_child_index] > @heap[max_index]
max_index = right_child_index
end
if max_index != index
@heap[index], @heap[max_index] = @heap[max_index], @heap[index]
sift_down(max_index)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment