Skip to content
Advertisement

Merge two arrays in alternate fashion

I am trying to merge to arrays of int type with the same size. Here’s my code

public class classA
{
static int[] mergeArray(int[] arr1, int arr2[])
{
   int arr3[] = new int[arr1.length+ arr2.length];
   int count = 0;
   for(int i = 0; i < arr1.length; i++){
       arr3[count] = arr1[i];
       count++;
       arr3[count] = arr2[i];
    }
    for(int i = 0; i < arr3.length; i++){

        System.out.print(arr3[i]);
    }
   return arr3;
}

public static void main(String[] args) throws IOException
{
    int arr1[] = {1,2,3};
    int arr2[] = {4,5,6};
    int arr3[] = mergeArray(arr1,arr2);
}
}

When I try printing the numbers in first for loop, it gives me 1,4,2,5,3,6 which the correct output. But, When I try printing it outside the first for loop it gives me output 1,2,3,6,0,0. Can someone help me? TIA

Advertisement

Answer

In your for loop, when you copy from arr2 you need to increment your count.

arr3[count] = arr2[i];
count++;

You could also simplify your code a bit like,

static int[] mergeArray(int[] arr1, int[] arr2) {
    int[] arr3 = new int[arr1.length * 2];
    int count = 0;
    for (int i = 0; i < arr1.length; i++) {
        arr3[count++] = arr1[i];
        arr3[count++] = arr2[i];
    }
    return arr3;
}

And print in main like

int arr3[] = mergeArray(arr1, arr2);
System.out.println(Arrays.toString(arr3));

or in Java 8+, use a flatMap and IntStream like

static int[] mergeArray(int[] arr1, int[] arr2) {
    return IntStream.range(0, arr1.length)
            .flatMap(i -> IntStream.of(arr1[i], arr2[i])).toArray();
}

for the same result.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement