Simple heap (priority queue) implementation in Ruby. It provides
push
,pop
,peek
, andpush_pop
.
- Max Heap Implementation: Ensures that the largest element is always at the top.
- Essential Heap Operations: Supports
push
,pop
,peek
, andpush_pop
. - Bulk Initialization: Initialize the heap with an array of elements.
You can initialize a new heap with an array of elements. The first element of the array represents the size of the heap, followed by the heap elements.
heap = Heapq.new([3, 1, 4, 1, 5, 9, 2, 6, 5])
Add a new element to the heap. The heap maintains the max heap property after insertion.
heap.push(7)
Remove and return the top (largest) element from the heap.
max = heap.pop
puts max # Output: 9
Push a new element onto the heap and then pop and return the top element in a single operation. This is more efficient than performing push followed by pop.
max = heap.push_pop(8)
puts max # Output: 8
View the top element without removing it from the heap.
top = heap.peek
puts top # Output: 7
Retrieve the number of elements currently in the heap.
size = heap.size
puts size # Output: 8
Add this line to your application's Gemfile
:
gem 'heapq', '~> 1.0'
The gem is available as open source under the terms of the MIT License.