Golang Merge Sort Algorithm

1. Introduction

Merge Sort is a divide-and-conquer sorting algorithm. It works by recursively splitting the list into two halves until each sub-list consists of a single element, and then merging these smaller lists in sorted order to produce larger, fully sorted lists.

2. Implementation Steps

1. If the list has one or no element, it's already sorted.

2. Divide the list recursively into two halves until each sublist has a single element.

3. Merge the sublists to produce a new, sorted list.

3. Implementation in Golang

package mainimport ("fmt")// Merge merges two sorted sub-arraysfunc Merge(arr []int, l, m, r int) {n1 := m - l + 1n2 := r - m// Create temp arraysL := make([]int, n1)R := make([]int, n2)// Copy data to temp arrays L[] and R[]for i := 0; i < n1; i++ {L[i] = arr[l+i]}for j := 0; j < n2; j++ {R[j] = arr[m+1+j]}// Merge the temp arrays back into arr[l..r]i, j, k := 0, 0, lfor i < n1 && j < n2 {if L[i] <= R[j] {arr[k] = L[i]i++} else {arr[k] = R[j]j++}k++}// Copy the remaining elements of L[], if there are anyfor i < n1 {arr[k] = L[i]i++k++}// Copy the remaining elements of R[], if there are anyfor j < n2 {arr[k] = R[j]j++k++}}// MergeSort sorts the array using merge sort algorithmfunc MergeSort(arr []int, l, r int) {if l < r {// Find the middle pointm := l + (r-l)/2// Sort first and second halvesMergeSort(arr, l, m)MergeSort(arr, m+1, r)Merge(arr, l, m, r)}}func main() {data := []int{38, 27, 43, 3, 9, 82, 10}fmt.Println("Original array:", data)MergeSort(data, 0, len(data)-1)fmt.Println("Sorted array:  ", data)}

Output:

Original array: [38 27 43 3 9 82 10]Sorted array:   [3 9 10 27 38 43 82]

Explanation:

1.Merge is a helper function that takes in an array and its left, middle, and right indices. It merges two sorted sub-arrays of the given array defined froml tom andm+1 tor.

2. Temporary arraysL andR are used to store the two halves to be merged.

3. TheMergeSort function is a recursive function that sorts the input array. It divides the array into two halves, sorts them usingMergeSort, and then merges them using theMerge function.

4. In themain function, an array is initialized, displayed in its original state, sorted usingMergeSort, and then displayed in its sorted state.

5.Merge Sort is a stable sort with a time complexity of O(n log n) in all three cases (worst, average, and best).

This offers a thorough guide to implementing and understanding the Merge Sort algorithm in Golang.


Comments