So I was trying to run the following code which is to merge two sorted arrays into one sorted array. However it keeps giving me an arrayIndexOutOfBound
exception. I want to prevent that exception.
public class SortArray {
public static void main(String[] args){
SortArray sa = new SortArray();
// create two arrays
int[] a = {1, 2, 3, 4, 5};
int[] b = {6, 7, 8, 9, 10};
int[] merge = sa.mergeArray(a, b);
for (int i = 0; i < merge.length; i++) {
System.out.print(merge[i] + " ");
}
}
public int[] mergeArray(int[] arr1, int[] arr2){
int arr1Length = arr1.length;
int arr2Length = arr2.length;
int[] merge = {}; // the merged array
int i, j;
int k = 0;
// when the index of both arrays are within array length
for (i = 0, j = 0; i < arr1.length && j < arr2Length;) {
if (arr1[i] < arr2[j]) {
merge[k] = arr1[i];
i++;
k++;
}else if (arr1[i] > arr2[j]) {
merge[k] = arr2[j];
j++;
k++;
}
}
// when arra1 is the remaining array
if (i < arr1Length) {
merge[k] = arr1[i];
i++;
k++;
}
// when array2 is the remaining error
if (j < arr2Length) {
merge[k] = arr2[j];
j++;
k++;
}
return merge;
}
}
Can anybody help me? Thanks!