I have written code to merge two sorted arrays in Java.
public class MergeSortedArrays {
public static int[] my_array = {3, 4, 6, 10, 11, 15};
public static int[] alices_array = {1, 5, 8, 12, 14, 19};
public static void main(String[] args) {
// TODO Auto-generated method stub
int length = my_array.length + alices_array.length;
int[] new_array = new int[length];
int i = 0;
int j = 0;
int count = 0;
while (count < length) {
if(my_array[i] < alices_array[j] ) {
new_array[count] = my_array[i];
i++;
} else {
new_array[count] = alices_array[j];
j++;
}
count++;
}
for(int k=0;k<length;k++) {
System.out.println(new_array[k]);
}
}
}
But I am getting this error-
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at MergeSortedArrays.main(MergeSortedArrays.java:15)
One array is exhausted before merging is completed. How can I handle this case?