Skip to content

Instantly share code, notes, and snippets.

@Legion112
Created April 14, 2025 11:29
Show Gist options
  • Save Legion112/51b64d7cdb06d773e573f96f9eb81268 to your computer and use it in GitHub Desktop.
Save Legion112/51b64d7cdb06d773e573f96f9eb81268 to your computer and use it in GitHub Desktop.
Go Generic Heap
package GenericHeap
import (
"container/heap"
)
// GenericHeap is a wrapper over heap.Interface using generics
type GenericHeap[T any] struct {
data []T
lessFunc func(i, j T) bool
}
func (h *GenericHeap[T]) Init() {
heap.Init(h)
}
func (h *GenericHeap[T]) Len() int { return len(h.data) }
func (h *GenericHeap[T]) Less(i, j int) bool { return h.lessFunc(h.data[i], h.data[j]) }
func (h *GenericHeap[T]) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] }
func (h *GenericHeap[T]) TypedPush(x T) {
heap.Push(h, x)
}
func (h *GenericHeap[T]) Push(x any) { h.data = append(h.data, x.(T)) }
func (h *GenericHeap[T]) TypedPop() T {
return heap.Pop(h).(T)
}
func (h *GenericHeap[T]) Pop() any {
n := len(h.data)
x := h.data[n-1]
h.data = h.data[:n-1]
return x
}
func (h *GenericHeap[T]) Top() T {
return h.data[0]
}
func NewHeap[T any](lessFunc func(a, b T) bool) *GenericHeap[T] {
return &GenericHeap[T]{lessFunc: lessFunc}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment