Golang program to insert an element into a priority queue


When working with go language there may be cases such as sorting, managing urgent events such as job scheduling, and more where you need to prioritize the element based on their urgency number. In this article, we will write a Go language program to insert an element into a priority queue.

A priority queue is a type of queue in which every stored element has a priority. The elements are added in the priority queue using the enqueue operation and removed from the queue using the dequeue operation.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Algorithm

  • Step 1 − This program imports fmt and main as necessary packages. Create a struct called Item with two fields named value of type string and priority of type int.

  • Step 2 − Define a type called PriorityQueue, which is a slice of Item to implement the priority queue. Then, create a new Item with the given value and priority.

  • Step 3 − Call the upHeapify method to restore the heap property by moving the newly inserted item to the heap and Iterate the given index until the root of the heap.

  • Step 4 − In the main, create an empty priority queue using the make function. Iterate over the priority queue and remove items from the queue and print their values

  • Step 5 − Insert element to the priority queue and call the upHeapify function.

  • Step 6 − Print the values by iterating over the priority queue.

  • Step 7 − Implement the downHeapify function to restore heap property.

Example 1

In this example, we will write a Go language program to insert an element in the queue using the insert method of the container/heap package.

package main

import (
   "container/heap"
   "fmt"
)

type Item struct {
   value    string 
   priority int    
   index    int    
}

type PriorityQueue []*Item

func (piq PriorityQueue) Len() int {
   return len(piq)
}
func (piq PriorityQueue) Less(i, j int) bool {
   return piq[i].priority < piq[j].priority
}
func (piq PriorityQueue) Swap(i, j int) {
   piq[i], piq[j] = piq[j], piq[i]
   piq[i].index = i
   piq[j].index = j
}
func (piq *PriorityQueue) Push(x interface{}) {
   item := x.(*Item)
   item.index = len(*piq)
   *piq = append(*piq, item)
}
func (piq *PriorityQueue) Pop() interface{} {
   old := *piq
   n := len(old)
   item := old[n-1]
   item.index = -1
   *piq = old[0 : n-1]
   return item
}
func (piq *PriorityQueue) Insert(value string, priority int) {
   item := &Item{
      value:    value,
      priority: priority,
   }
   heap.Push(piq, item)
}
func main() {
   piq := make(PriorityQueue, 0)

   piq.Insert("Chocolates", 30)
   piq.Insert("Fruits", 20)
   piq.Insert("Dry Fruits", 10)

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

Output

Value: Dry Fruits, Priority: 10
Value: Fruits, Priority: 20
Value: Chocolates, Priority: 30

Example 2

In this example, we will write a Go language program to insert an element into a priority queue using a binary heap.

package main

import "fmt"

type Item struct {
    value    string
    priority int
}

type PriorityQueue []Item

func (piq *PriorityQueue) Insert(value string, priority int) {
    item := Item{
        value:    value,
        priority: priority,
    }
    *piq = append(*piq, item)
    piq.upHeapify(len(*piq) - 1)
}

func (piq *PriorityQueue) upHeapify(index int) {
    for index > 0 {
        parentIndex := (index - 1) / 2
        if (*piq)[index].priority >= (*piq)[parentIndex].priority {
            break
        }
        (*piq)[index], (*piq)[parentIndex] = (*piq)[parentIndex], (*piq)[index]
        index = parentIndex
    }
} 

func main() {
    piq := make(PriorityQueue, 0)

    piq.Insert("Chocolates", 30)
    piq.Insert("Fruits", 20)
    piq.Insert("Vegetables", 10)

    for len(piq) > 0 {
        item := piq.Pop()
        fmt.Printf("Value: %s, Priority: %d\n", item.value, item.priority)
    }
}

func (piq *PriorityQueue) Pop() Item {
    n := len(*piq)
    item := (*piq)[0]
    (*piq)[0] = (*piq)[n-1]
    *piq = (*piq)[:n-1]
    piq.downHeapify(0)
    return item
}

func (piq *PriorityQueue) downHeapify(index int) {
    n := len(*piq)
    for {
        leftChildIndex := 2*index + 1
        rightChildIndex := 2*index + 2
        smallestIndex := index

        if leftChildIndex < n && (*piq)[leftChildIndex].priority < (*piq)[smallestIndex].priority {
            smallestIndex = leftChildIndex
        }
        if rightChildIndex < n && (*piq)[rightChildIndex].priority < (*piq)[smallestIndex].priority {
            smallestIndex = rightChildIndex
        }

        if smallestIndex == index {
            break
        }

        (*piq)[index], (*piq)[smallestIndex] = (*piq)[smallestIndex], (*piq)[index]
        index = smallestIndex
    }
}

Output

Value: Vegetables, Priority: 10
Value: Fruits, Priority: 20
Value: Chocolates, Priority: 30

Conclusion

In this article we compiled and executed the program of inserting an element in the priority queue using two examples. In the first example we used a container/heap package and in the second example we used a binary heap to create a priority queue and insert elements in it.

Updated on: 06-Jul-2023

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements