我不确定为什么合并操作的左大小和右大小似乎不适用于左 = 0、中 = 0 和右 = 1。由于这些计算,左右数组的切片不起作用有任何意义。合并排序算法假定这些数组之一必须具有值才能使其位于代码的合并部分。这导致索引错误:(
https://play.golang.org/p/Fmj4xNQTL8W
package main
import (
"fmt"
)
func merge(arr []int, l, mid, r int) {
leftSize := mid - l + 1
rightSize := r - mid
left := arr[l:mid]
right := arr[mid+1 : r]
fmt.Printf("l:%v, m:%v, r:%v\n", l, mid, r)
fmt.Printf("left: size:%v arr:%v, right: size:%v arr:%v\n", leftSize, l, rightSize, r)
/*
i = left array pointer
j = right array pointer
k = original array pointer
*/
i, j, k := 0, 0, l
for i < leftSize && j < rightSize {
if left[i] <= right[j] {
arr[k] = left[i]
i++
k++
} else {
arr[k] = right[j]
j++
k++
}
}
for i < leftSize {
arr[k] = left[i]
i++
k++
}
for j < rightSize {
arr[k] = right[j]
j++
k++
}
}
func mergeSort(arr []int, left, right int) {
if left >= right {
return
}
// mid done this way to avoid overflows
mid := left + (right-left)/2
mergeSort(arr, left, mid)
mergeSort(arr, mid+1, right)
merge(arr, left, mid, right)
}
func main() {
tc := []int{99, 212, 23, 3, 1, 10}
mergeSort(tc, 0, len(tc)-1)
fmt.Printf("%v", tc)
}
相关分类