Documentation
¶
Overview ¶
Package priorityqueue provides a generic priority queue backed by a binary heap.
The priority is determined by a user-supplied Less function:
less(a, b) returns true if a has higher priority than b
Min-heap (smallest value = highest priority):
pq := priorityqueue.New(func(a, b int) bool { return a < b })
Max-heap (largest value = highest priority):
pq := priorityqueue.New(func(a, b int) bool { return a > b })
Custom struct with priority field:
type Task struct { Name string; Priority int }
pq := priorityqueue.New(func(a, b Task) bool { return a.Priority > b.Priority })
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type PriorityQueue ¶
type PriorityQueue[T any] struct { // contains filtered or unexported fields }
PriorityQueue is a generic heap-backed priority queue. The zero value is not usable; use New or NewFromSlice to construct one.
func New ¶
func New[T any](less func(a, b T) bool) *PriorityQueue[T]
New returns an empty PriorityQueue using the provided Less function to determine priority. less(a, b) must return true when a has higher priority than b (i.e. a should be popped before b).
func NewFromSlice ¶
func NewFromSlice[T any](less func(a, b T) bool, values []T) *PriorityQueue[T]
NewFromSlice builds a PriorityQueue pre-populated with the given values. The slice is copied; the original is not modified. Time complexity: O(n).
func (*PriorityQueue[T]) IsEmpty ¶
func (pq *PriorityQueue[T]) IsEmpty() bool
IsEmpty reports whether the queue has no elements.
func (*PriorityQueue[T]) Len ¶
func (pq *PriorityQueue[T]) Len() int
Len returns the number of elements in the queue.
func (*PriorityQueue[T]) Peek ¶
func (pq *PriorityQueue[T]) Peek() T
Peek returns the highest-priority element without removing it. Panics if the queue is empty. Time complexity: O(1).
func (*PriorityQueue[T]) Pop ¶
func (pq *PriorityQueue[T]) Pop() T
Pop removes and returns the highest-priority element. Panics if the queue is empty. Time complexity: O(log n).
func (*PriorityQueue[T]) Push ¶
func (pq *PriorityQueue[T]) Push(v T)
Push adds v to the queue. Time complexity: O(log n).