implementing 3-way partition quicksort

This commit is contained in:
2020-06-08 11:56:48 -05:00
parent 9d501eb6c8
commit 9f0ce5056d

View File

@@ -12,27 +12,30 @@ public class QuickSorterThreeWay extends QuickSorter{
//edit this to use three-way partition //edit this to use three-way partition
@Override @Override
private void quickSort(int lowIndex, int highIndex){ void quickSort(int lowIndex, int highIndex){
if(compare(lowIndex,highIndex)<0){ if(compare(lowIndex,highIndex)<0){
int pivot = partition(lowIndex, highIndex);
quickSort(lowIndex, pivot-1);
quickSort(pivot+1, highIndex);
}
}
//edit this to use three way partition
@Override
private int partition(int lowIndex, int highIndex){
int pivot=numbers[highIndex]; int pivot=numbers[highIndex];
int i = lowIndex-1; int lessThan = lowIndex;
for(int j=lowIndex;j<highIndex;j++){ int greaterThan = highIndex;
if(compare(numbers[j],pivot)<0){ int i = greaterThan-1;
i++; while(i>lessThan){
swap(i,j); int comp = compare(pivot, numbers[i]);
if(comp>0){
swap(i, greaterThan);
i--;
greaterThan--;
}
else if(comp<0){
swap(i, lessThan);
lessThan++;
}
else{
i--;
} }
} }
swap(i+1, highIndex); quickSort(lowIndex, lessThan-1);
return i+1; quickSort(greaterThan+1, highIndex);
}
} }