当给定一个元素数组时,我应该如何计算算法执行的元素比较次数?
这并不像只需将计数器添加到分区方法一样简单。
private void partition(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high-low)/2];
// Divide into two lists
while (i <= j) {
if (array[i] < pivot) {
i++;
compareCount++; //it's not as easy as just adding this here
}
else if (numbers[j] > pivot) {
j--;
compareCount++;
}
else (i <= j) {
exchange(i, j);
i++;
j--;
}
}
您不能这样做,因为它仅计算刚刚进行的比较,而不考虑在其评估为false时进行的任何比较。
我尝试将
if(array [i]<pivot)
更改为while(array [i]<pivot)
(对于j也是如此),但如果以这种方式进行,我感觉还是错过了某些东西。