package kata func MergeSort(data []int) []int { if len(data) <= 1 { return data } mid := len(data) / 2 return merge(MergeSort(data[:mid]), MergeSort(data[mid:])) } func merge(left []int, right []int) []int { result := make([]int, 0, len(left)+len(right)) for len(left) > 0 && len(right) > 0 { if left[0] < right[0] { result = append(result, left[0]) left = left[1:] } else { result = append(result, right[0]) right = right[1:] } } if len(left) > 0 { result = append(result, left...) } if len(right) > 0 { result = append(result, right...) } return result }
- package kata
func merge_sort(slice []int) []int {length := len(slice)if length < 2 {return slice- func MergeSort(data []int) []int {
- if len(data) <= 1 {
- return data
- }
mid := (length) / 2return merge(merge_sort(slice[:mid]), merge_sort(slice[mid:]))}func merge(left, right []int) []int {size, l, r := len(left)+len(right), 0, 0slice := make([]int, size, size)- mid := len(data) / 2
- return merge(MergeSort(data[:mid]), MergeSort(data[mid:]))
- }
for i := 0; i < size; i++ {if l > len(left)-1 && r <= len(right)-1 {slice[i] = right[r]r++} else if r > len(right)-1 && l <= len(left)-1 {slice[i] = left[l]l++} else if left[l] < right[r] {slice[i] = left[l]l++- func merge(left []int, right []int) []int {
- result := make([]int, 0, len(left)+len(right))
- for len(left) > 0 && len(right) > 0 {
- if left[0] < right[0] {
- result = append(result, left[0])
- left = left[1:]
- } else {
slice[i] = right[r]r++- result = append(result, right[0])
- right = right[1:]
- }
- }
return slice}func MergeSort(arr []int) []int {return merge_sort(arr)- if len(left) > 0 {
- result = append(result, left...)
- }
- if len(right) > 0 {
- result = append(result, right...)
- }
- return result
- }