Even checking the right condition Go throwing, panic: runtime error: index out of range [3] with length 3

Even checking the right condition Go throwing, panic: runtime error: index out of range [3] with length 3

package main

import "fmt"

func mergeSortedArray(arr1 []int, arr2 []int) []int {

    var mergedArr []int
    lengthArr := len(arr1) + len(arr2)
    fmt.Println(lengthArr)

    i := 0
    j := 0
    //Check input
    if len(arr1) == 0 {
        return arr2
    }

    if len(arr2) == 0 {
        return arr1
    }

    for c := 0; c < lengthArr; c++ {
        if arr1[i] >= arr2[j] {
            mergedArr = append(mergedArr, arr2[j])
            j++
        } else {
            mergedArr = append(mergedArr, arr1[i])
            i++
        }
    }
    return mergedArr

}

func main() {

    arr1 := []int{0, 3, 31}
    arr2 := []int{4, 6, 30}

    m := mergeSortedArray(arr1, arr2)
    fmt.Println(m)
    //Exp output : 0,3,4,6,30,31
}

重要的注意事项,同时进行以下操作 for c := 0; c < lengthArr-1; c++

它正在给出结果:0,3,4,6,30.

任何人都可以查看这段代码,这将是一个很大的帮助。 提前致谢。

你的算法有问题,你假设你的数组是均匀分布的。

您需要检查是否已经添加了一个数组中的所有条目,然后添加第二个数组的其余条目

func mergeSortedArray(arr1 []int, arr2 []int) []int {
    var mergedArr []int
    lengthArr := len(arr1) + len(arr2)
    fmt.Println(lengthArr)

    i := 0
    j := 0
    //Check input
    if len(arr1) == 0 {
        return arr2
    }

    if len(arr2) == 0 {
        return arr1
    }

    for c := 0; c < lengthArr; c++ {
        if i >= len(arr1) {
            mergedArr = append(mergedArr, arr2[j:len(arr2)]...)
            break
        } else if j >= len(arr2) {
            mergedArr = append(mergedArr, arr1[i:len(arr1)]...)
            break
        } else if arr1[i] >= arr2[j] {
            mergedArr = append(mergedArr, arr2[j])
            j++
        } else {
            mergedArr = append(mergedArr, arr1[i])
            i++
        }
    }
    return mergedArr

}