简体   繁体   中英

Recursive max stack overflow error

I am trying to write a 3 input recursive program for max and min for a data structures class. I am getting a stack overflow error. I cannot tell if I am going off the end of the array, but I shouldn't be as far as my understanding goes. Any help would be appreciated. Here is my code:

class Extrema {

    // maxArray()
    // returns the largest value in int array A
    // p is position zero, r is position length-1
    static int maxArray(int[] A, int p, int r) {
        int q;
        if (p == r) {
            return A[p];
        } else {
            q = (p + r)/2;
            return max(maxArray(A, p, q-1), maxArray(A, q+1, r));
        }
    }

    // max()
    // returns the largest value of two ints
    private static int max(int a, int b) {
        return a > b ? a : b;
    }

    // main()
    public static void main(String[] args) {
        int[] B = {-1, 2, 6, 3, 9, 2, -3, -2, 11, 5, 7};
        System.out.println( "max = " + maxArray(B, 0, B.length-1) );  // output: max = 11
    } 
}

Change this code

if (p == r) {
    return A[p];
}

to

if (p >= r) {
    return A[p];
}

and note that when you call statement

return max(maxArray(A, p, q-1), maxArray(A, q+1, r));

you lose q element, so call

return max(maxArray(A, p, q), maxArray(A, q+1, r));

Either do it non recursive since recursion really does not make any sense here:

static int maxArray(int[] A, int p, int r)  {
    int max = A[p];
    for (int i = p + 1; i <= r; i++) {
        if (A[i] > max)
            max = A[i];
    }
    return max;
}

Or if you insist on some kind of recursion use your code existing with just a minor change:

return max(maxArray(A, p, q), maxArray(A, q+1, r));

Note the call to the first maxArray function now gets passed q and not q-1 as end index.

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