Trying to implement an algorithm with Java where the method will take an input array, starting index and ending index, and will recursively reverse the array with a swap function. The method will properly swap the base case, but it will return that state as the answer.
public static char[] stringRecursion(char[] a, int p, int q) {
if (q < p) {
return swap(a, p, q);
}
return stringRecursion(a, p+1, q-1);
}
public static char[] swap(char[] a, int p, int q) {
char temp = a[p];
a[p] = a[q];
a[q] = temp;
return a;
}
You should easily fix it by yourself with debugging...
Anyway, if I understand correctly what you want to achieve, you want to swap the two indices every time the recursive function is called, and simply stop when q < p
. In your code you are swapping the indices only when q
is less then p
, which should be the condition for stopping.
Furthermore you don't really want to return the array in your functions, since when you change values in an array passed in the parameters, it automatically updates the array you passed in the main function! See Is Java "pass-by-reference" or "pass-by-value"? to understand a little more about.
Example:
public static void stringRecursion(char[] a, int p, int q) {
if(q < p) return;
swap(a, p, q);
stringRecursion(a, p+1, q-1);
}