Golang program to represent a Binary Heap


A Binary heap is a binary tree-based data structure which is used to implement priority queues and sorting algorithms. In this article, we will write a Go language program to represent a Binary Heap. There are two types of heaps: max and min heap. In max heap the value of nodes is greater or equal to their children and in min heap the value of nodes is less than its children.

Syntax

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.

Algorithm

  • Step 1 − Create an Insert method to add values to the heap and call the percolateUp method, After the Insert method implement the Delete method.”.

  • Step 2 − If the heap is empty, create a panic with “Heap is empty, Store the minimum element in a variable, then, replace the root with the last element of the heap and reduce the size of the heap.

  • Step 3 − Call the percolateDown method with the index of the root and Implement the percolateUp method which takes an index as input

  • Step 4 − Then, calculate the parent index of the given index and Swap the values until the current index is greater than 0 and and the value is smaller than parent value. Create the percolateDown method to move index down the heap.

  • Step 5 − Calculate the indices of the left and right child of the current index and then consider the smallest index as the current index and update it if left child index is smaller than the value at the current index.

  • Step 6 − Swap the values at the current index and the smallest index if the smallest index is still the current index. Update the current index to the smallest index

  • Step 7 − In the main, create a new object of BinaryHeap using the NewBinaryHeap function. Then, insert elements into the heap using the Insert() method and print them on the console.

  • Step 8 − Print the updated elements of the heap after deletion on the console using the Println() function from the fmt package

Example

In this example, we will write a Go language program to represent a Binary Heap where we will use the Binary struct to refer to the heap.

package main

import (
   "fmt"
)
type BinaryHeap struct {
   array []int
   size  int
}
func NewBinaryHeap() *BinaryHeap {
   return &BinaryHeap{}
}
func (h *BinaryHeap) Insert(value int) {
   h.array = append(h.array, value)
   h.size++
   h.percolateUp(h.size - 1)
}
func (h *BinaryHeap) Delete() int {
   if h.size == 0 {
      panic("Heap is empty")
   }

   min := h.array[0]
   h.array[0] = h.array[h.size-1]
   h.array = h.array[:h.size-1]
   h.size--
   h.percolateDown(0)

   return min
}

func (h *BinaryHeap) percolateUp(index int) {
   parentIndex := (index - 1) / 2

   for index > 0 && h.array[index] < h.array[parentIndex] {
      h.array[index], h.array[parentIndex] = h.array[parentIndex], h.array[index]
      index = parentIndex
      parentIndex = (index - 1) / 2
   }
}

func (h *BinaryHeap) percolateDown(index int) {
   for {
      leftChildIndex := 2*index + 1
      rightChildIndex := 2*index + 2
      smallestIndex := index

      if leftChildIndex < h.size && h.array[leftChildIndex] < h.array[smallestIndex] {
         smallestIndex = leftChildIndex
      }

      if rightChildIndex < h.size && h.array[rightChildIndex] < h.array[smallestIndex] {
         smallestIndex = rightChildIndex
      }

      if smallestIndex == index {
         break
      }

      h.array[index], h.array[smallestIndex] = h.array[smallestIndex], h.array[index]
      index = smallestIndex
   }
}

func main() {
   heap := NewBinaryHeap()

   heap.Insert(50)
   heap.Insert(30)
   heap.Insert(80)
   heap.Insert(20)
   heap.Insert(10)

   fmt.Println("The Heap elements given here are:", heap.array)
   fmt.Println("The minimum element deleted here is:", heap.Delete())
   fmt.Println("The Heap elements after deletion are:", heap.array)
}

Output

The Heap elements given here are: [10 20 80 50 30]
The minimum element deleted here is: 10
The Heap elements after deletion are: [20 30 80 50]

Conclusion

In this article we have discussed how we can represent a binary heap in go language. We compiled and executed the program of representing a Binary Heap using an example in which we used a BinaryHeap struct to print the heap elements.

Updated on: 05-Jul-2023

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements