简体   繁体   中英

Java Stackoverflow Error Recursion

This code I have written works great until a certain input size. If the input gets too large, I get a "java.lang.StackOverflowError". I have read some other entries on stackoverflow regarding this topic and I think I got an error in my recursion- but I can't find it. Here is the code:

public int partition(int[] A, int l, int r, int x){

    int i = l-1;
    int j = r;
    int exchange;

    while(i <= j){
        while(A[i] > x){
            i++;
        }

        while(j >= i && A[j] <= x){
            j--;
        }

        if(i < j){
            exchange = A[i];
            A[i] = A[j];
            A[j] = exchange;
        }
    }

    if(A[i] < A[r]){
        exchange = A[i];
        A[i] = A[r];
        A[r] = exchange;
    }

    return i;
}

public void quicksort(int[] A, int l, int r){
    int pivot = 0;
    int x = 0;

    if(l < r){
        x = A[r];
        pivot = partition(A, l, r, x);
        quicksort(A, l, pivot-1);
        quicksort(A, pivot+1, r);
    }
}

If the input gets too large

What exactly do you mean by "too large"? Every recursion that is deep enough could end up with stack overflow, because stack is used to keep all local variables of your recursive method on all levels of recursion.

This is intrinsic disadvantage of recursion, and a reason why iterative implementation usually outperforms recursive.

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