My Java quick sort algorithm is throwing a stack overflow error on arrays that are long such as an array of length 100,000. I am finding my pivot using the median of three method. I have my median(median) and quick sort method(qSortB) enclosed. Does anyone know why this error is occurring? Thank you for you help.
//Finding the pivot using the median of three method
public int median(int low, int high){
int p;
int temp;
int min= list[low];
//System.out.println("min: "+ min);
int med=list[(high+low)/2];
//System.out.println("med: "+ med);
int max= list[high];
//System.out.println("max: "+ max);
if ((min >= med) != (min >= max)) {
p= min;
}
else if ((med >= min) != (med >= max)) {
p= med;
temp=list[(high+low)/2];
list[(high+low)/2] = list[low];
list[low] =temp;
}
else {
p= max;
temp=list[high];
list[high] = list[low];
list[low] =temp;
}
return p;
}
public void qSortB(int low, int high){
if(low>=high|| high<=low){
return;
}
else{
int left=low+1;
int right=high;
int pivot =median(low,high);
//System.out.println("Pivot: "+ pivot);
int pi=low;
while(left<=right){
while(left <len && list[left]< pivot){
comp++;
left++;
}
while(right >-1 && list[right] >pivot){
comp++;
right--;
}
if(left <len && right>-1 && left<=right){
comp++;
// System.out.println("Swapping "+list[right]
// +" with " + list[left]);
int temp=list[left];
list[left] = list[right];
list[right] = temp;
left++;
right--;
swap++;
//print();
}
if(left>right){
int temp= list[left-1];
list[left-1]= pivot;
list[pi]= temp;
pi=left-1;
swap++;
qSortB(low,pi-1);
qSortB(pi+1,high);
}
}
}
}