How do I implement merge sort in Go?

Merge sort is a classic divide-and-conquer algorithm that efficiently sorts an array or slice by dividing it into smaller sub-arrays, sorting those, and merging them back together. Below is an implementation of merge sort in Go.

package main import "fmt" // merge function merges two sorted slices func merge(left, right []int) []int { var result []int i, j := 0, 0 // Merge until one slice is empty for i < len(left) && j < len(right) { if left[i] < right[j] { result = append(result, left[i]) i++ } else { result = append(result, right[j]) j++ } } // Add remaining elements (if any) result = append(result, left[i:]...) result = append(result, right[j:]...) return result } // mergeSort function recursively sorts the slice func mergeSort(slice []int) []int { if len(slice) < 2 { return slice } mid := len(slice) / 2 left := mergeSort(slice[:mid]) right := mergeSort(slice[mid:]) return merge(left, right) } func main() { arr := []int{38, 27, 43, 3, 9, 82, 10} sortedArr := mergeSort(arr) fmt.Println("Sorted array:", sortedArr) }

Merge Sort Go Programming Sorting Algorithm Divide and Conquer Go Merge Sort Example