-4
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
}

Important catch, while doing below operation for c := 0; c < lengthArr-1; c++

it is giving result : 0,3,4,6,30.

Can anyone look into this code, it will be a great help. Thanks in advance.

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
Alok Tripathi
  • 874
  • 10
  • 9
  • 2
    you have arrays of length = 3 & you are looping over `len(arr) + len(arr2)` which is equal to 6, that justifies the error. – Arindam Nayak Oct 05 '20 at 09:42
  • The arrays only have 3 elements, and you are trying to access the fourth. You get panic. What is your question? – super Oct 05 '20 at 09:44

1 Answers1

1

There is a problem with your algorithm, you are assuming your arrays are equally distributed.

You need to check if you already added all entries from one array then add the rest of the second one

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

}
MoiioM
  • 1,914
  • 1
  • 10
  • 16