Home > front end >  StackOverflowError while trying to Reverse an Array using Recursion
StackOverflowError while trying to Reverse an Array using Recursion

Time:09-26

I've written a recursive method for reversing an array.

It produces a StackOverflowError, and I just can't figure out why. I'm sure it's something simple, but I've been stuck here for 2 hours trying to fix it.

My code:

public static void reverseArray(char[] input, int i, int j) {
    char temp;
    if (i >= j) return;
    
    else if (i < j) {
        temp = input[i];
        input[i] = input[j];
        input[j] = temp;
        reverseArray(input, i  , j--);
    }
}

CodePudding user response:

You should change the post-increment/post-decrement to pre-increment/pre-decrement in the recursive call:

reverseArray(input,   i, --j);

i would change only the value of i that exists in the scope of the current method call, but the argument received by the recursive call would be the initial value of i (same holds true for j).

So basically you're passing the same indices and for that reason getting a StackOverflowError.

Also note that there's no need to wrap the recursive case with else if.

public static void reverseArray(char[] input, int i, int j) {
    
    if (i >= j) return;
    
    char temp = input[i];
    input[i] = input[j];
    input[j] = temp;
    
    reverseArray(input,   i, --j);
}

Alternatively, as @Slaw has suggested in the comments, to avoid confusion you can explicitly add/subtract one while making a recursive call:

reverseArray(input, i   1, j - 1);

CodePudding user response:

Try fixing (x , y--) to ( x, --y)

  • Related