I have three arrays like the below:
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[] = {9,10,11,12};
I want to merge the above arrays by taking the first element from each array, then the second, etc. to get the below result:
int d[] = {1,5,9,2,6,10,3,7,11,4,8,12};
I have tried the following code, but as can be observed from the output it concatenates the data from each of the array rather than grouping elements under the same index together. How can I fix that?
My code:
public class MergeTwoArrays2 {
public static void main(String[] args) {
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[] = {9,10,11,12};
int a1 = a.length;
int b1 = b.length;
int c1 = c.length;
int d1 = a1 + b1 +c1;
int[] d = new int[d1];
for (int i = 0; i < a1; i = i + 1) {
d[i] = a[i];
}
for (int i = 0; i < b1; i = i + 1) {
d[a1 + i] = b[i];
}
for (int i = 0; i < c1; i = i + 1) {
d[a1 + b1 + i] = c[i];
}
for (int i = 0; i < d1; i = i + 1) {
System.out.println(d[i]);
}
}
}
Output:
[1,2,3,4,5,6,7,8,9,10,11,12]
Expected Output:
[1,5,9,2,6,10,3,7,11,4,8,12]