1

I have two array which I like to merge in a manner so my output should like this

Can we also go for multidimesional array ?

public class MeregTwoArray {

public static int[] mergeArray(int[] a, int[] b) {
    int length = (a.length + b.length);
    int result[] = new int[length];
    for (int i = 0; i <= a.length-1;) {
        result[i] = a[i];
        for (int j = 0; j <= b.length-1;) {
            result[i + 1] = b[j];
            j++;
            break;
        }
        i++;
    }
    return result;
}

public static void main(String[] args) {
    int a[] = {1, 3, 5, 6, 7, 8};
    int b[] = {4, 2, 7, 6, 4, 2};
    int result[] = mergeArray(a, b);

    for (int i = 0; i <= result.length - 1; i++) {
        System.out.println(result[i]);
    }
}

}

current output: 1 3 5 6 7 8 4 0 0 0 0 0

Expected Output:

1 4 3 2 5 7 6 6 7 4 8 2

user10753505
  • 99
  • 11

2 Answers2

0

You can maintain 2 indices, one for the "merged" array, and the index for your loop's iteration. Because you're merging, you'll need to increment the target index by 2 in each iteration:

public static int[] mergeArray(int[] a, int[] b) {
    int length = (a.length + b.length);
    int result[] = new int[length];

    for (int i = 0, e = 0; i <= a.length - 1; i++, e += 2) {
        result[e] = a[i];
        result[e + 1] = b[i];
    }

    return result;
}

Which outputs the expected 1 4 3 2 5 7 6 6 7 4 8 2

ernest_k
  • 44,416
  • 5
  • 53
  • 99
-1

Does this help?

public static int[] mergeArray(int[] a, int[] b) {
   int result[] = new int[a.length + b.length];
   int targetIdx = 0;  // result arrray index counter
   int i, j; 


   for(i = 0, j = 0; i <= a.length-1; ) {
      result[targetIdx] = a[i++]; // put element from first array 
      if(j < b.length) { // if second array element is there
         result[++targetIdx] = b[j++]; // put element from second array
      }
     targetIdx++;
  }

  // If b.length > a.length
  while(j < b.length) {
      result[taargetIdx++] = b[j++];
  }
  return result;
}
roottraveller
  • 7,942
  • 7
  • 60
  • 65