Golang program to insert an element into a binary heap


Inserting an element in a binary heap means to add an extra element to the heap and maintain the heap property at the same time.In this Go language article, we will write a program to insert an element into a binary heap. It is a binary tree-based data structure which follows the heap properties. Heaps are of two types: min heap and max heap.

In the min heap the value of the parent node is less than the value of its children and in the max heap the value of the parent node is more than the value of its children. They are used to implement priority queues, sorting algorithms and graph algorithms.

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.

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 − Create a NewHeap function that creates a new heap with an empty array. Create an Insert method which takes elements as inputs

  • Step 2 − In the first step,append the new element to the end of the array. Call the siftUp method with the index of the newly inserted element

  • Step 3 − The siftUp method takes an index as input and moves the element up the heap until it reaches the correct position

  • Step 4 − Then, calculate the index of the parent using (index - 1) / 2. Check whether the current index is greater than 0 and the parent's value is greater than the current element

  • Step 5 − If the above condition is satisfied, swap the parent and the current element. Update the index with the parent index. Then, recalculate the parent index

  • Step 6 − In the main, create a new heap object using NewHeap(). Create a list of values to be added to the heap

  • Step 7 − Iterate over the list of values and insert them into the heap using the Insert method and, print the heap elements on the console using the Println method from the fmt package

Example 1

In this example, we will write a Go language program to insert an element into a binary heap by assuming a min-heap. Here, we use the Insert method to insert elements in the heap.

package main

import "fmt"

type Heap struct {
   array []int
}

func NewHeap() *Heap {
   return &Heap{
      array: []int{},
   }
}

func (h *Heap) Insert(element int) {
   h.array = append(h.array, element)
   currentIndex := len(h.array) - 1

   for currentIndex > 0 {
      parentIndex := (currentIndex - 1) / 2
      if h.array[parentIndex] <= h.array[currentIndex] {
         break
      }
      h.array[parentIndex], h.array[currentIndex] = h.array[currentIndex], h.array[parentIndex]
      currentIndex = parentIndex
   }
}

func main() {
   heap := NewHeap()
   values := []int{60, 90, 40, 70, 20, 80, 10}

   for _, value := range values {
      heap.Insert(value)
   }

   fmt.Println("The Heap elements are:", heap.array)
}

Output

The Heap elements are: [10 40 20 90 70 80 60]

Example 2

In this example, we will write a Go language program to insert an element in the binary heap using the siftUp method which inserts the element in the end of heap and compares them with the parent.

package main

import "fmt"

type Heap struct {
   array []int
}

func NewHeap() *Heap {
   return &Heap{
      array: []int{},
   }
}

func (h *Heap) Insert(element int) {
   h.array = append(h.array, element)
   h.siftUp(len(h.array) - 1)
}

func (h *Heap) siftUp(index int) {
   parent_index := (index - 1) / 2

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

func main() {
   heap := NewHeap()
   values := []int{60, 90, 40, 70, 20, 80, 10}

   for _, value := range values {
      heap.Insert(value)
   }

   fmt.Println("The Heap elements are:", heap.array)
}

Output

The Heap elements are: [10 40 20 90 70 80 60]

Conclusion

In this article we have discussed how we can insert an element into binary heap. Here we compiled and executed two examples. In the first example, we assumed a min-heap and in the second example we used a siftUp method. Some of the applications of binary heap are priority queue, heap sort, dijkstra algorithm,and more these are just few examples of binary heapin go language.

Updated on: 05-Jul-2023

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements