When I send to this method an array of size > 900000, I get a StackOverflowError
about half of the time. Please, help me understand why this is happening and how to fix it.
public static void quicksort2(int[] xs, int lo, int hi){
int h,l,p,t;
if (lo<hi){
l = lo;
h = hi;
p = xs[hi];
do {
while( (l<h) && (xs[l] <= p) )
l= l+1;
while( (h > l) && (xs[h] >= p))
h = h-1;
if (l < h){
t = xs[l];
xs[l] = xs[h];
xs[h] = t;
}
} while (l<h);
xs[hi] = xs[l];
xs[l] = p;
quicksort2(xs, lo, l-1);
quicksort2(xs, l+1,hi);
}
}
The specific error I get is:
Exception in thread "main" java.lang.StackOverflowError
at sort.Sorters.quicksort2(Sorters.java:117)
at sort.Sorters.quicksort2(Sorters.java:117)
at sort.Sorters.quicksort2(Sorters.java:118)
at sort.Sorters.quicksort2(Sorters.java:117)
at sort.Sorters.quicksort2(Sorters.java:117)
And then a bunch more of this same thing. The two lines referenced are the recursive calls.