简体   繁体   中英

StackOverflowError while trying to Reverse an Array using Recursion

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

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM