Skip to content

Instantly share code, notes, and snippets.

@kamal-github
Created March 15, 2024 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-github/c9e147441029d6188541469f88e8ea21 to your computer and use it in GitHub Desktop.
Save kamal-github/c9e147441029d6188541469f88e8ea21 to your computer and use it in GitHub Desktop.
generic_priority_queue
package collections
type Item[T any] struct {
Item T
Priority int
Index int
}
type PriorityQueue[T any] []*Item[T]
func (pq PriorityQueue[T]) Len() int { return len(pq) }
func (pq PriorityQueue[T]) Less(i, j int) bool {
return pq[i].Priority < pq[j].Priority
}
func (pq PriorityQueue[T]) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].Index = i
pq[j].Index = j
}
func (pq *PriorityQueue[T]) Push(x any) {
n := len(*pq)
item := x.(*Item[T])
item.Index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue[T]) Pop() any {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.Index = -1 // for safety
*pq = old[0 : n-1]
return item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment