I am trying to merge two sorted arrays recursively, and I can merge the first characters in each array, but then I return the sorted array, and my recursive call stops. Can someone help me understand how to better structure my code, although I believe my logic is correct. Here is my code:
public static char[] mergeArrays( char[] A, char[] B) {
char[] answer = new char[ 0]; // an empty array to have something to return
return mergeArraysHelper(A, B, 0);
}
public static char[] mergeArraysHelper(char[] a, char[] b, int index) {
char[] newArr = new char[a.length+b.length];
if(index > newArr.length) {
return newArr;
}
//check to see if both arrays are still populated
if(index < a.length && index < b.length) {
newArr[index] = a[index];
newArr[index+1] = b[index];
} else {
//check to see if array a is empty
if(index > a.length && index < b.length) {
newArr[index] = b[index];
} else {
//check to see if array b is empty
if(index < a.length && index > b.length) {
newArr[index] = a[index];
} else {
return newArr;
}
}
}
mergeArraysHelper(a, b, ++index);
return newArr;
}
You should pass newArr into each recursive call, do not create a new instance every time. You do not need to return anything from the recursive call at all in this case. Your wrapper method will look like this:
public static char[] mergeArrays( char[] A, char[] B) {
char[] answer = new char[ 0]; // an empty array to have something to return
char[] newArr = new char[ A.length + B.length];
mergeArraysHelper(newArr, A, B, 0);
return newArr;
}
I like this solution:
public static char[] mergeArrays(char[] a, char[] b) {
if(a.length == 0)
return b;
if(b.length == 0)
return a;
char[] newArr = new char[a.length + b.length];
if(a[0] <= b[0]) {
newArr[0] = a[0];
char[] merged = mergeArrays(Arrays.copyOfRange(a, 1, a.length), b);
System.arraycopy(merged, 0, newArr, 1, merged.length);
} else {
newArr[0] = b[0];
char[] merged = mergeArrays(a, Arrays.copyOfRange(b, 1, b.length));
System.arraycopy(merged, 0, newArr, 1, merged.length);
}
return newArr;
}
But if you don't want to create a new array every time you might prefer doing something like this:
public static char[] mergeArrays( char[] A, char[] B) {
char[] sorted = new char[A.length + B.length];
mergeArraysHelper(A, B, sorted, 0);
return sorted;
}
public static void mergeArraysHelper(char[] a, char[] b, char[] sorted, int index) {
if(a.length == 0) {
System.arraycopy(b, 0, sorted, index, b.length);
return;
}
if(b.length == 0) {
System.arraycopy(a, 0, sorted, index, a.length);
return;
}
if(a[0] <= b[0]) {
sorted[index] = a[0];
mergeArraysHelper(Arrays.copyOfRange(a, 1, a.length), b, sorted, index + 1);
} else {
sorted[index] = b[0];
mergeArraysHelper(a, Arrays.copyOfRange(b, 1, b.length), sorted, index + 1);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.