C++ 快速排序中的计数比较
我正在尝试计算C++ 快速排序中的计数比较,c++,c,quicksort,counting,C++,C,Quicksort,Counting,我正在尝试计算快速排序的比较次数。对于最坏情况,它显示n*n-1/2比较。因此,对于顺序为87654321的8个输入,应该是28个比较。然而,在我的程序中有30个比较。我试着打印比较结果,但最后一次比较重复了三次。任何人都能找到这个代码的错误吗 #include<iostream.h> #include<conio.h> int ar[10000]; int pivot; int temp; int partition(int x, int y); void quicks
快速排序
的比较次数。对于最坏情况,它显示n*n-1/2比较。因此,对于顺序为87654321的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;
}
#包括
#包括
国际ar[10000];
int轴;
内部温度;
int分区(intx,inty);
无效快速排序(int f,int l);
整数计数=0;
int i;
整数指数;
void main(){
clrsc();
int i;
对于(i=0;i<8;++i){
cin>>ar[i];
}
快速排序(0,7);
cout您还可以使用任意容器的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;
class-LessCompare
{
公众:
LessCompare():m_计数器(0u){}
模板
布尔运算符(){
++m_计数器;
返回左侧<右侧;
}
无符号比较()常量{return m_counter;}
私人:
非灵敏m_计数器;
};
std::vector容器;
比较;
std::sort(container.begin()、container.end()、std::ref(compare));
std::cout对于HP/Microsoft的std::sort,如果处于调试模式,则会进行两个额外的比较,以检查比较是否“对我来说似乎是在做28-请看,您的代码未注释,变量名简洁且不清楚,并且充满全局(!);这需要解决。更干净的代码更容易调试——这是这样做的一个合理理由。(另一个原因是它会让其他程序员更愿意阅读您的代码!)