Search code examples
javasortingstack-overflow

I am trying to write a quickSort method as part of an assignment, but I keep getting a StackOverflow error in Java


This is the code for my sorting attempt. After running for about ten minutes in Eclipse's debugger mode, I got a lot of StackOverFlow errors. This was my output display:

Exception in thread "main" java.lang.StackOverflowError

at TestSorter.Tester.sort(Tester.java:6)

... (x112 repetitions of at TestSorter.Tester.sort(Tester.java:49))

at TestSorter.Tester.sort(Tester.java:49)

public static int[] sort(int[] a) {
                           int prod = (a.length)/2, b = lessThan(a, prod), c = greaterThan(a, prod), d = equalTo(a, prod);
    int[] first, last, mid;
    first = new int[b];
    last = new int[c];
    mid = new int[d];
    int[] fina = new int[a.length];
    int f = 0, l = 0, m = 0;

    if (isSorted(a))
        return a;

    for (int x = 0; x < a.length; x++) {
        if (a[x] < prod) {
            first[f] = a[x];
            f++;
        }
        else if (a[x] > prod) {
            last[l] = a[x];
            l++;
        }
        else if (a[x] == prod) {
            mid[m] = a[x];
            m++;
        }
    }
    if (m == a.length)
        return a;

                           first = sort(first);

    last = sort(last);

    for (int x = 0; x < b; x++) {
        fina[x] += first[x];
    }
    for (int x = 0; x < d; x++) {
        fina[x + b] = mid[x];
    }
    for (int x = 0; x < c; x++) {
        fina[x + b + c] = last[x];
    }

    return fina;
}

My support methods are as follows:

private static int lessThan(int[] a, int prod) {
    int less = 0;
    for (int x = 0; x < a.length; x++) {
        if (a[x] < prod) {
            less++;
        }
    }
    return less;
}

private static int greaterThan(int[] a, int prod) {
    int greater = 0;
    for (int x = 0; x < a.length; x++) {
        if (a[x] > prod) {
            greater++;
        }
    }
    return greater;
}

private static int equalTo(int[] a, int prod) {
    int equal = 0;
    for (int x = 0; x < a.length; x++) {
        if (a[x] == prod) {
            equal++;
        }
    }
    return equal;
}

private static boolean isSorted(int[] a) {
    for (int x = 0; x < a.length - 1; x++) {
        if (a[x] > a[x + 1])
            return false;
    }
    return true;
}

Solution

  • Presumably the trouble is that your "prod" is not within the domain of your array. Thus either "first" or "last" is the same size as the input array, and you have an infinite recursion. Try setting prod to be an element in the array you are trying to sort.