I have two sorted arrays. I need to connect both of them into one new sorted array:
int[] arr1 = {1,2,3,6,8};
int[] arr2 = {4,5,9,12,208,234};
printArr(allSort(arr2,arr1));
}
public static int[] allSort(int[] arr, int[] arr3) {
int[] newArr = new int[arr.length + arr3.length];
int j = 0;
int k = 0;
for (int i = 0; i < newArr.length - 1; i++) {
if(j == arr3.length){
newArr[i] = arr[k];
k++;
}
if(k == arr.length){
newArr[i] = arr3[j];
j++;
}
if(arr[k] > arr3[j]){
newArr[i] = arr3[j];
j++;
} else if (arr[k] < arr3[j]) {
newArr[i] = arr[k];
k++;
}
}
return newArr;
}
I tried to build an array that has a length equal to the length of the both arrays summed together and then run a loop on it.
However, this code returns the error: AArrayIndexOutOfBoundsException: 5
.