package main import "fmt" func merge(left, right []int) []int { result := []int{} i, j := 0, 0 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++ } } result = append(result, left[i:]...) result = append(result, right[j:]...) return result } func mergeSort(arr []int) []int { if len(arr) <= 1 { return arr } mid := len(arr) / 2 left := mergeSort(arr[:mid]) right := mergeSort(arr[mid:]) return merge(left, right) } func main() { arr := []int{5, 3, 8, 4, 2} sorted := mergeSort(arr) fmt.Println(sorted) }
The merge sort splits the array recursively until single elements remain, then merges them in sorted order. The final sorted array is [2 3 4 5 8].
The divide step splits the array into smaller parts until each part has only one element, which is trivially sorted.
func merge(left, right []int) []int { result := []int{} i, j := 0, 0 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++ } } result = append(result, left[i:]...) result = append(result, right[j:]...) return result }
The loop condition uses <= which allows i or j to equal the length of the slice, causing index out of range when accessing left[i] or right[j].
type Item struct { value int id int } func merge(left, right []Item) []Item { result := []Item{} i, j := 0, 0 for i < len(left) && j < len(right) { if left[i].value <= right[j].value { result = append(result, left[i]) i++ } else { result = append(result, right[j]) j++ } } result = append(result, left[i:]...) result = append(result, right[j:]...) return result } func mergeSort(arr []Item) []Item { if len(arr) <= 1 { return arr } mid := len(arr) / 2 left := mergeSort(arr[:mid]) right := mergeSort(arr[mid:]) return merge(left, right) } func main() { arr := []Item{{2,1}, {3,2}, {2,3}, {1,4}} sorted := mergeSort(arr) for _, v := range sorted { fmt.Printf("{value:%d, id:%d} ", v.value, v.id) } }
Merge sort is stable because it uses <= in comparison, so items with equal values keep their original order. Option A shows this order preserved.
Merge sort divides the array into halves log n times and merges all elements each level in O(n), resulting in O(n log n) time complexity.
