I'm not sure why left size and right size of the merge operations don't seem to work for for left = 0, mid = 0 and right = 1. Because of these calcs the slicing of the left and right array don't make any sense. The mergesort algo assumes that one of these arrays has to have values for it to even be in the merge portion of the code. This is leading to index errors :(
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
", l, mid, r)
fmt.Printf("left: size:%v arr:%v, right: size:%v arr:%v
", 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)
}