1

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--);
    }
}

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that fixed the error! Now I just have to figure out why it reverses the array multiple times until it repeats the same word as the original input
@SushiSlicer Your code would fine with the fix I've mentioned (++i and --j). See the online demo. I've added a print statement and removed some redundancy.
@SushiSlicer Personally, I would use i + 1 and j - 1, just to make it completely clear.
@Slaw Agree, it's good to keep the code simple, included this idea into the answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.