当给定一个元素数组时,如何计算算法执行的元素比较量?如何计算Quicksort算法中元素比较的数量?
这不像向分区方法添加计数器那么简单。
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),但我觉得我仍然错过了某些东西,如果我这样做。
相反,你必须指望交换的数量。我认为我无法解释你真正想要的东西,可以请澄清一点。还有,如果部分你为什么要做++ comparecounter? – Algorithmist 2011-03-01 03:46:13
我把它留在那里最初是因为当对所有相等元素的数组进行排序时,这是我能够判断元素何时被排序的唯一方法。 – David 2011-03-01 04:10:53
当你在做while(array [i]
Algorithmist
2011-03-01 05:55:17