Sobes.tech
Middle

Tell about a priority queue.

sobes.tech AI

Answer from AI

A priority queue is a data structure that allows storing elements with an assigned priority and extracting the element with the highest priority first.

Unlike a regular queue (FIFO), where elements are processed in the order they arrive, in a priority queue, the order is determined by the priority value.

In Go, the container/heap package is often used to implement a priority queue, providing an interface for creating a heap. A heap is an efficient data structure for implementing a priority queue.

Example of implementing a priority queue in Go:

package main

import (
    "container/heap"
    "fmt"
)

type Item struct {
    value    string
    priority int

    index    int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
    return pq[i].priority > pq[j].priority // higher priority is at the front
}
func (pq PriorityQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
    pq[i].index = i
    pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
    n := len(*pq)
    item := x.(*Item)
    item.index = n
    *pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil
    item.index = -1
    *pq = old[0 : n-1]
    return item
}

func main() {
    pq := make(PriorityQueue, 0)
    heap.Init(&pq)

    heap.Push(&pq, &Item{value: "task1", priority: 3})
    heap.Push(&pq, &Item{value: "task2", priority: 5})
    heap.Push(&pq, &Item{value: "task3", priority: 1})

    for pq.Len() > 0 {
        item := heap.Pop(&pq).(*Item)
        fmt.Printf("Processing %s with priority %d\n", item.value, item.priority)
    }
}

In this example, tasks with higher priority are processed first.

Tell about a priority queue. — Golang - sobes.tech