Documentation
¶
Overview ¶
Package binaryheap implements the generic binary heap.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BinaryHeap ¶
Example ¶
bh := NewBinaryHeap[int]() bh.Push(17, 50, 32, 93, 8, 9, 69, 4, 26, 19) fmt.Println(bh.Peek()) v, ok := bh.Pop() if ok { fmt.Println(v) }
Output: 93 93
func NewBinaryHeap ¶
func NewBinaryHeap[T cmp.Ordered]() *BinaryHeap[T]
NewBinaryHeap creates a new instance of BinaryHeap. The binary heap is a complete binary tree where each node is bigger or equal to its children. The elements are stored in an array, and the heap property is maintained with every new element added to the heap.
func NewBinaryHeapWithCapacity ¶
func NewBinaryHeapWithCapacity[T cmp.Ordered](capacity int) *BinaryHeap[T]
NewBinaryHeapWithCapacity creates a new instance of BinaryHeap with the specified capacity. The capacity is the maximum number of elements that the binary heap can hold without reallocating its underlying slice.
func (*BinaryHeap[T]) Cap ¶
func (bh *BinaryHeap[T]) Cap() int
Cap returns the capacity of the binary heap.
The capacity is the maximum number of elements that the binary heap can hold without reallocating its underlying slice.
func (*BinaryHeap[T]) Clip ¶
func (bh *BinaryHeap[T]) Clip()
Clip removes unused capacity from the binary heap. It is useful when the capacity of the binary heap is no longer needed and can be reclaimed by the garbage collector.
Clip does not change the length of the binary heap; it merely resizes the capacity.
It is safe to call Clip even if the binary heap is already at its capacity.
func (*BinaryHeap[T]) IsEmpty ¶
func (bh *BinaryHeap[T]) IsEmpty() bool
IsEmpty checks if the binary heap is empty.
It returns true if the binary heap has no elements, and false otherwise.
The time complexity of this method is O(1).
func (*BinaryHeap[T]) Len ¶
func (bh *BinaryHeap[T]) Len() int
Len returns the number of elements in the binary heap.
The time complexity of this method is O(1).
func (*BinaryHeap[T]) Peek ¶
func (bh *BinaryHeap[T]) Peek() (T, bool)
Peek returns the biggest element in the binary heap without removing it and true. If the binary heap is empty, it returns a zero value of type T and false.
The time complexity of this method is O(1).
func (*BinaryHeap[T]) Pop ¶
func (bh *BinaryHeap[T]) Pop() (T, bool)
Pop removes and returns the biggest element from the binary heap. If the binary heap is empty, it returns a zero value of type T and false.
The time complexity of this method is O(log n), where n is the number of elements in the heap.
func (*BinaryHeap[T]) Push ¶
func (bh *BinaryHeap[T]) Push(xs ...T)
Push adds one or more elements to the binary heap.
The Push method takes a variadic parameter xs, which represents the elements to be added to the heap.
The time complexity of adding each element is O(log n), where n is the number of elements in the heap.