问题
I implemented a simple quick sort (code below) to count the average and worst comparison made by quicksort. I declared a global variable to hold the counter for comparisons. I placed 3 counters in different positions that I thought would count the comparisons, the problem is the counter sum does not match the theoretical value of the total number of comparisons made by quick sort. I tried to solve this problem for hours but came up short. I really appreciate if you can point me where I should put the counters and why I should place them there. I assumed a counter should go where ever a comparison is made. apparently I'm wrong.
public int[] quickSort(int[] array, int start, int end){
if (start < end){
counter++;//1st comparison here
int pivot;
pivot = Partition(array, start, end);
quickSort(array, start, pivot - 1);
quickSort(array, pivot + 1, end );
}
return array;
}
private int Partition(int[] array, int start, int end) {
int pivot = array[end];
int i = start - 1;
for(int j = start; j <= end - 1; j++){
counter++;//2nd comparison here
if (array[j] <= pivot){
counter++;//3rd comparison here
i = i + 1;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i+1];
array[i+1] = array[end];
array[end] = temp;
return i + 1;
}
回答1:
For the theory, only the comparisons of array elements are counted, not the comparisons of indices to the bounds, so you should only leave the second counter++;
(you need to increment the counter independently of the result of the comparison).
Then there is the question against which theoretical values you compare. There are different implementations of quicksort which use slightly different numbers of comparisons. In particular, your choice of the pivot makes no attempt to avoid extreme values, so this implementation will easily degrade to O(n^2) behaviour.
来源:https://stackoverflow.com/questions/9646233/counting-quicksort-comparisons