在快速排序中计算比较
Counting comparisons in quicksort
我正在尝试计算quicksort
的比较次数。对于最坏的情况,它显示了n*n-1/2的比较。因此,对于顺序为8 7 6 5 4 3 2 1的8个输入,应该是28个比较。然而,在我的程序中有30个比较。我试着打印比较,结果都很好,但最后一次比较重复了三次。有人能找到这个代码的错误吗?
#include<iostream.h>
#include<conio.h>
int ar[10000];
int pivot;
int temp;
int partition(int x, int y);
void quicksort(int f, int l);
int count = 0;
int i;
int index;
void main() {
clrscr();
int i;
for (i = 0; i < 8; ++i) {
cin >> ar[i];
}
quicksort(0, 7);
cout << "nThe sum is " << sum;
getch();
}
void quicksort(int f, int l) {
if (f == l)
return 0;
if (f < l) {
pivot = partition(f, l);
quicksort(f, pivot - 1);
quicksort(pivot + 1, l);
}
}
int partition(int f, int l) {
index = ar[f];
i = f + 1;
for (int j = f + 1; j <= l; ++j) {
if (ar[j] < index) {
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
++i;
}
}
i = i - 1;
temp = ar[f];
ar[f] = ar[i];
ar[i] = temp;
return i;
}
您还可以使用带有比较器的任意容器的STL分类器,该比较器只对比较进行计数。
class LessCompare
{
public:
LessCompare() : m_counter ( 0u ) {}
template<typename T>
bool operator() ( T const& lhs, T const& rhs ) const {
++m_counter;
return lhs < rhs;
}
unsigned compares() const { return m_counter; }
private:
unsigend m_counter;
};
std::vector < T > container;
LessCompare compare;
std::sort ( container.begin(), container.end(), std::ref ( compare ) );
std::cout << "Compares: " << compare.compares() << std::endl;
但是,我不确定std::sort
是否是一个快速排序。
您可以简单地改进快速排序,它使用任意的函子进行比较并统计一些统计信息。
在HP/Microsoft的std::sort的情况下,如果处于调试模式,则需要进行两次额外的比较,以检查比较是否为"<"而不是"<="。它通过检查<b、 则b<a.如果您是在调试模式下构建的,请尝试在发布模式下构建,看看是否有帮助。
相关文章:
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 为什么组合的上限和下限比较的计算结果总是为 true?
- 为什么将三个变量与 == 一起比较会计算为 false?
- 自定义迭代器:如果 a 和 b 的行为不同,如何正确处理距离计算和相等比较
- 计算变量并进行比较
- 计算搜索比较C++
- 如何在选择排序中计算比较?
- 计算在堆排序中完成的比较次数
- 几个比较怎么可能比一些计算慢
- C++日期比较并不总是计算出相同的逻辑值
- 通过比较数组中的相邻元素来计算交换次数
- 如何计算二叉搜索树中的比较
- 计算选择排序中的比较次数时出错
- 计算比较数和QuickSort C 中的移动
- 计算QuickSort算法中的组件明智比较数量
- c++:旋转锁或互斥对象比较(简单计算)
- 使用构造函数来比较/计算用户输入
- 在快速排序中计算比较
- 计算快速排序中的比较次数
- 我该如何计算在二进制搜索树中进行的比较