-2

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;
   }
  • 4
    It looks like it's time to do some debugging. If you're not sure how, please look at: 1) [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/), as well as 2) [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Hovercraft Full Of Eels Sep 12 '22 at 21:19
  • 2
    What exactly happens that's the problem? – Louis Wasserman Sep 12 '22 at 21:26
  • Off topic: Why use recursion? Why not iteration? – Old Dog Programmer Sep 13 '22 at 01:22
  • return swap(a, p, q); is wrong "return" is only used at the end of a method to exit after last line. Also, to obtain "swap" each recursion is done a=swap(a, p, q); – Samuel Marchant Sep 13 '22 at 05:48
  • Sorry, first time posting and fairly new to recursion and coding in general. I know there is a fairly simple answer through iterating, but I wanted to see if I could come to a recursive answer, and I was stumped on it for quite sometime. Thank you all for the advice!! – Jake Munroe Sep 14 '22 at 21:41

1 Answers1

0

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);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Crih.exe
  • 502
  • 4
  • 16
  • 1
    Thank you very much, I was stumped on this problem for quite a while, but I will definitely spend more time debugging and the learning the process in the future. I can see where I went wrong and I appreciate your time to answer this! Thanks again! – Jake Munroe Sep 14 '22 at 21:45