Golang program to implement merge sort


In this Golang article, we will learn how to implement Merge Sort in Golang using three different methods recursions, iteration and goroutines. Merge sort is one of the most efficient sorting Algorithms that uses the divide and conquer approach to sort a list of elements.

Syntax

func copy(dst, str[] type) int

The copy function in go language is used to copy the values of one source array to the destination array and returns the number of elements copied as the result. It takes the two arrays as an argument.

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 − First we need to import the fmt package.

  • Step 2 − Now, define a function called mergeSort that accepts an array of integers as argument to it and returns the sorted array.

  • Step 3 − Inside the function if the length of the array is less than or equal to 1 then return the complete array as it is not possible to sort a single element in the array. Then find the middle point of the given array.

  • Step 4 − Call the mergeSort() function recursively on the left half of the array and store the result to a variable called left.

  • Step 5 − Similarly call mergeSort() function again recursively on the right half of the array and store the result to a variable called right.

  • Step 6 − Call the merge function with the left and right arrays as input and return the result.

  • Step 7 − The merge() function accepts both the left and right arrays as arguments and combines them together in a single array by using for loops and if conditionals.

  • Step 8 − Now, start the main() function. Inside the main() initialize the array to be sorted and print them on the screen.

  • Step 9 − Further, call the mergeSort() function by passing the array initialized as argument to the function. Store the result obtained by the function in a variable and print them on the screen.

Example 1

Recursion is most common method to implement the merge sort. In this method we divide the given data into two halves then sort each half recursively. Then by merging the sorted halves together we implement the merge sort completely.

package main

import "fmt"

func mergeSort(arr []int) []int {
   if len(arr) <= 1 {
      return arr
   }
   middle := len(arr) / 2
   left := mergeSort(arr[:middle])
   right := mergeSort(arr[middle:])
   return merge(left, right)
}

func merge(left, right []int) []int {
   result := make([]int, len(left)+len(right))
   i, j := 0, 0
   for k := 0; k < len(result); k++ {
      if i >= len(left) {
         result[k] = right[j]
         j++
      } else if j >= len(right) {
         result[k] = left[i]
         i++
      } else if left[i] < right[j] {
         result[k] = left[i]
         i++
      } else {
         result[k] = right[j]
         j++
      }
   }
   return result
}

func main() {
   arr := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("The given unsorted array is:", arr)
   sorted := mergeSort(arr)
   fmt.Println("The sorted array is:", sorted)
}

Output

The given unsorted array is: [5 2 6 3 1 4]
The sorted array is: [1 2 3 4 5 6]

Example 2

In this Example we will use the iteration variables to implement the merge sort of an array. In this method we will use various inbuilt functions like copy() and len() along with for loops and if conditionals to implement the result.

package main

import "fmt"

func mergeSort(arr []int) []int {
   if len(arr) <= 1 {
      return arr
   }
   size := 1
   for size < len(arr) {
      for left := 0; left < len(arr)-1; left += size * 2 {
         middle := left + size - 1
         right := min(left+size*2-1, len(arr)-1)
         merged := merge(arr[left:middle+1], arr[middle+1:right+1])
         copy(arr[left:right+1], merged)
      }
      size *= 2
   }
   return arr
}

func merge(left, right []int) []int {
   result := make([]int, len(left)+len(right))
   i, j := 0, 0
   for k := 0; k < len(result); k++ {
      if i >= len(left) {
         result[k] = right[j]
         j++
      } else if j >= len(right) {
         result[k] = left[i]
         i++
      } else if left[i] < right[j] {
         result[k] = left[i]
         i++
      } else {
         result[k] = right[j]
         j++
      }
   }
   return result
}

func min(a, b int) int {
   if a < b {
      return a
   }
   return b
}

func main() {
   arr := []int{5, 2, 6, 3, 1, 4}
   fmt.Println("The given unsorted array is:", arr)
   sorted := mergeSort(arr)
   fmt.Println("The obtained sorted array is:", sorted)
}

Output

The given unsorted array is: [5 2 6 3 1 4]
The obtained sorted array is: [1 2 3 4 5 6]

Example 3

In this Example we will use the goroutines to implement the merge sort. Goroutines can be defined as the lightweight threads that allow us to use concurrent programming.

package main

import "fmt"

func mergeSort(arr []int, c chan []int) {
   if len(arr) <= 1 {
      c <- arr
      return
   }
   middle := len(arr) / 2
   leftChan := make(chan []int)
   rightChan := make(chan []int)
   go mergeSort(arr[:middle], leftChan)
   go mergeSort(arr[middle:], rightChan)
   left := <-leftChan
   right := <-rightChan
   c <- merge(left, right)
}

func merge(left, right []int) []int {
   result := make([]int, len(left)+len(right))
   i, j := 0, 0
   for k := 0; k < len(result); k++ {
      if i >= len(left) {
         result[k] = right[j]
         j++
      } else if j >= len(right) {
         result[k] = left[i]
         i++
      } else if left[i] < right[j] {
         result[k] = left[i]
         i++
      } else {
         result[k] = right[j]
         j++
      }
   }
   return result
}

func main() {
   arr := []int{15, 21, 6, 30, 16, 43}
   fmt.Println("Unsorted array:", arr)
   c := make(chan []int)
   go mergeSort(arr, c)
   sorted := <-c
   fmt.Println("Sorted array:", sorted)
}

Output

Unsorted array: [15 21 6 30 16 43]
Sorted array: [6 15 16 21 30 43]

Conclusion

We have successfully compiled and executed a go language program to implement the merge along with the Examples. In this article we have used three programs. in the first program we are using the concept of recursion to implement the result while in the second and third programs we are using the internal library functions along with the goroutines respectively.

Updated on: 05-Apr-2023

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements