Golang program to sort a slice of integers using merge sort with concurrency


In this article, we will write Go language programs to sort a slice of integers using merge sort with concurrency. It is a process which makes the parts of a program run independently and parallelly enhancing the efficiency of the program. Go routines and channels are used to execute concurrency.

Merge sort is a divide and conquer algorithm used to sort the unsorted array or slice by dividing the input slice into smaller sub-slices, individually sort them recursively and then merge them into a single slice which is sorted.

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.

Algorithm

  • This program imports main, fmt and sync package in the program.

  • Create a function named merge_integers which takes two slices left and right as arguments which will be merged into a single sorted slice.

  • In this step, create a slice named output with the length equal to the sum of the lengths of left and right slice.

  • Then, initialize two variables named i and j to 0 which represent the indices of the left and right slices.

  • In this step, use a for loop to sort the slice of integers.

  • Compare the elements at indices i and j in left and right and if left is less than right assign the smaller value to output[i+j].

  • Then, increment the index if less is less than right and j if right is less than left.

  • It continues this process until one of the slices is completely traversed.

  • After the loop is traversed, there might be some elements left in left or right slice which are later checked using if-else conditional and added to the resultant slice.

  • Finally, it returns the outputt slice, which contains the merged and sorted elements from left and right.

  • Create a merge Sort function to perform concurrency with the nums as parameter which denotes the slice to be sorted.

  • In this step, check If the length of the input slice is less than or equal to 1 return the input slice as it is already sorte.

  • Then, calculate the middle index of the nums slice and assign it to the mid variable.

  • In this step, create two empty slices, left and right, to store the left and right halves of the slices.

  • Then, initialize a sync.Wait Group and add a count of 2 to it using the Add method, as there will be two go routines running concurrently.

  • Then, use anonymous functions to create two go routines.

  • In the first go routine sort the left half of nums by recursively calling merge Sort on the slice nums[:mid] and store the output in the left slice.

  • In the second go routine sorts the right half of nums by recursively calling merge Sort on the slice nums[mid:] and stores the output in the right slice.

  • Use Wait method to wait for the go routines to complete the process.

  • After the go routines complete and the Wait Group counter reaches 0, merge the sorted left and right slices using the merge function and return the output.

  • Create a main function.

  • In the main create an unsorted slice of integers and store it inside the slice variable.

  • Then, call the merge Sort function on this slice to sort it.

  • Finally,tThe sorted result is printed to the console using the Println function from the fmt package.

Example

In this example, we will write a Go language program to sort a slice of integers by using go routines and channels with merge sort algorithm to implement concurrency.

package main

import (
	"fmt"
	"sync"
)

func merge_integers(left, right []int) []int {
	output := make([]int, len(left)+len(right))
	i, j := 0, 0

	for i < len(left) && j < len(right) {
		if left[i] <= right[j] {
			output[i+j] = left[i]
			i++
		} else {
			output[i+j] = right[j]
			j++
		}
	}

	for i < len(left) {
		output[i+j] = left[i]
		i++
	}

	for j < len(right) {
		output[i+j] = right[j]
		j++
	}

	return output
}

func mergeSort(nums []int) []int {
	if len(nums) <= 1 {
		return nums
	}

	mid := len(nums) / 2

	var left, right []int

	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		left = mergeSort(nums[:mid])
		wg.Done()
	}()

	go func() {
		right = mergeSort(nums[mid:])
		wg.Done()
	}()

	wg.Wait()

	return merge_integers(left, right)
}

func main() {
	slice := []int{90, 50, 10, 30, 80, 40, 20, 70, 60}
	fmt.Println("Unsorted:", slice)

	sorted := mergeSort(slice)
	fmt.Println("Sorted:", sorted)
}

Output

Unsorted: [90 50 10 30 80 40 20 70 60]
Sorted: [10 20 30 40 50 60 70 80 90]

Conclusion

We compiled and executed the program of sorting a slice of integers using merge sort by implementing concurrency with the help of an example which uses Go routine and channels. Hence, the program executed successfully.

Updated on: 04-Aug-2023

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements