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 29 30 31 32 33 34 35 36 37 38 39 40
| func mergeSort(nums []int) []int { if len(nums) == 1 { return nums } mid := len(nums) / 2 left := nums[0:mid] right := nums[mid:] orderLeft := mergeSort(left) orderRight := mergeSort(right) res := make([]int, 0, len(orderLeft)+len(orderRight)) i, j := 0, 0 for i < len(orderLeft) && j < len(orderRight) { if orderLeft[i] > orderRight[j] { res = append(res, orderRight[j]) j++ } else { res = append(res, orderLeft[i]) i++ } } for i < len(orderLeft) { res = append(res, orderLeft[i]) i++ } for j < len(orderRight) { res = append(res, orderRight[j]) j++ } return res }
|