Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stackoverflow error in quicksort

So I've been trying to implement a quicksort myself, but it generates a stackoverflowerror, but I can't seem to find what the cause is.

Can someone help me?

public static int partition(int[] a, int p, int q){
    int i = 0;
    for (int j = p; j < q; ++j){
        if(a[j] <= a[q]){
            int tmp = a[j];
            a[j] = a[i];
            a[i] = tmp;
            i++;
        }
    }
    int tmp = a[i];
    a[i] = a[q];
    a[q] = tmp;
    return i;
}

public static void qsort(int[] a, int p, int q){
    if(p < q){
        int x = partition(a, p, q);
        qsort(a, p, x - 1);
        qsort(a, x + 1, q);
    }
}

public static void main(String args[]){
    int[] a = {4, 6, 2, 9, 8, 23, 0, 7};

    qsort(a, 0, a.length - 1);

    for(int i : a){
        System.out.print(i + " ");
    }
}
like image 436
user1003208 Avatar asked Jan 20 '26 11:01

user1003208


2 Answers

There are several bugs, but the immediate one you're hitting is that in partition(), i is not constrained to be between p and q. You pretty quickly end up in a situation where p=2, q=3 yet the final value of i is 1. This results in infinite recursion as qsort() keeps calling itself with identical arguments.

like image 85
NPE Avatar answered Jan 23 '26 01:01

NPE


A stack overflow error means the stop condition for the recursion is never reached, in this case p < q is never true. Use a debugger, set a breakpoint for that line, and look for when qsort() is repeatedly recursively called with the same parameters.

like image 38
millimoose Avatar answered Jan 23 '26 01:01

millimoose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!