1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| func mergeSort(arr []int) []int { n := len(arr) if n <= 1 { return arr } mid := n / 2 left := mergeSort(arr[:mid]) right := mergeSort(arr[mid:]) return merge(left, right) } func merge(left, right []int) []int { res := make([]int, 0, len(left)+len(right))
for len(left) > 0 && len(right) > 0 { if left[0] <= right[0] { res = append(res, left[0]) left = left[1:] } else { res = append(res, right[0]) right = right[1:] } }
res = append(res, left...) res = append(res, right...) return res }
|