Created
March 15, 2024 06:55
-
-
Save kamal-github/c9e147441029d6188541469f88e8ea21 to your computer and use it in GitHub Desktop.
generic_priority_queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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