I'm attempting to implement a version of quick sort that uses a pivot calculated as follows:
pivot = ( a[start] + a[end] + a[size/2] ) / 3
ATM it works perfectly on array's of size 6 or less, however as soon as an array size of 7 or greater is sorted the program enters an infinite loop. My understanding of recursion isn't solid as of yet, so I suspect it's falling apart there. I know it enters a loop when checking indexes 4 and 6, and then continually checks ONLY those indexes
Edit: Added the call to quickSort(), and fixed some formatting
public static void quickSort(double[] list, int start, int end){
if (end - start > 1){
int pivot = split(list, start, end);
quickSort(list, start, pivot - 1);
quickSort(list, pivot + 1, end);
}
if ( (end - start) == 1){
if (list[start] > list[end]){
double temp = list[start];
list[start] = list[end];
list[end] = temp;
}
}
}
public static int split(double[] list, int start, int end){
// splitPoint = (a[begin] + a[end] + a[size/2]) / 3
int size = end - start + 1;
double pivotValue = (list[start] + list[end] + list[size/2]) / 3;
int leftPosition = start;
int rightPosition = end;
double temp = 0;
while (true){
// find a value to swap on the left side of pivot
while ( (leftPosition <= rightPosition) && (list[leftPosition] <= pivotValue) ){
leftPosition++;
}
// find a value to swap on the right side of pivot
while ( (rightPosition >= leftPosition) && (list[rightPosition] >= pivotValue) ){
rightPosition--;
}
// if positions pass each other
if (rightPosition < leftPosition){
break;
} else {
// swap values
temp = list[leftPosition];
list[leftPosition] = list[rightPosition];
list[rightPosition] = temp;
}
}
return rightPosition;
}
public static void main(String[] args){
double[] list = {7, 6, 5, 4, 3, 2, 1};
quickSort(list, 0, list.length-1);
}
if (end - start > 1){and just wait for one of the values to be negative.