Merge Two Sorted Array in Java, One
// merge two sorted array
public static Integer[] merge(Integer[] arr1, Integer[] arr2){
Integer[] array = null;
if( arr1 != null && arr2 != null){
int i=0, j = 0, k = 0;
int len1 = arr1.length;
int len2 = arr2.length;
array = new Integer[len1+len2];
while(k < len1 + len2) {
if( i >= len1) {
array[k] = arr2[j]; // i is out of bound
j++;
}
else if( j >= len2) {
array[k] = arr1[i]; // j is out of bound
i++;
}
else {
if(arr1[i] < arr2[j]) {
array[k] = arr1[i];
j i++;
}
else {
array[k] = arr2[j];
j++;
}
}
k++;
}
}
return array;
}
Merge Two Sorted Array in Java, Two
public static Integer[] mergeSortedArr(Integer[] a1, Integer[] a2){
int len1 = a1.length;
int len2 = a2.length;
Integer[] arr = new Integer[len1 + len2];
int i = 0, j = 0, k = 0;
while(i < len1 || j < len2){
if(i >= len1){
arr[k] = a2[j]; // i is out of bound
j++;
}else if(j >= len2){
arr[k] = a1[i]; // j is out of bound
i++;
}else{
if(a1[i] < a2[j]){
arr[k] = a1[i];
i++;
}else{
arr[k] = a2[j];
j++;
}
}
k++;
}
return arr;
}