implementing 3-way partition quicksort
This commit is contained in:
@@ -12,28 +12,31 @@ 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);
|
int pivot=numbers[highIndex];
|
||||||
quickSort(lowIndex, pivot-1);
|
int lessThan = lowIndex;
|
||||||
quickSort(pivot+1, highIndex);
|
int greaterThan = highIndex;
|
||||||
|
int i = greaterThan-1;
|
||||||
|
while(i>lessThan){
|
||||||
|
int comp = compare(pivot, numbers[i]);
|
||||||
|
if(comp>0){
|
||||||
|
swap(i, greaterThan);
|
||||||
|
i--;
|
||||||
|
greaterThan--;
|
||||||
|
}
|
||||||
|
else if(comp<0){
|
||||||
|
swap(i, lessThan);
|
||||||
|
lessThan++;
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
i--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
quickSort(lowIndex, lessThan-1);
|
||||||
//edit this to use three way partition
|
quickSort(greaterThan+1, highIndex);
|
||||||
@Override
|
|
||||||
private int partition(int lowIndex, int highIndex){
|
|
||||||
int pivot = numbers[highIndex];
|
|
||||||
int i = lowIndex-1;
|
|
||||||
for(int j=lowIndex;j<highIndex;j++){
|
|
||||||
if(compare(numbers[j],pivot)<0){
|
|
||||||
i++;
|
|
||||||
swap(i,j);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
swap(i+1, highIndex);
|
|
||||||
return i+1;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user