【发布时间】:2015-04-23 15:37:35
【问题描述】:
我编写了一个 C++ 程序,用于使用快速排序算法对数组进行排序。
程序还会统计排序过程中发生的数组元素比较次数。
我确定快速排序算法逻辑有效,但我不确定打印的比较次数是否正确...
如果有人能告诉我一种机制来确定给定输入中可能发生的数字数组元素比较,我将不胜感激。 任何带有比较计数的示例数组也将帮助我测试我的程序的正确性。
程序代码:
using namespace std;
//Partition Logic
int* partion(int *a,int l, int r,int counter){
//Initialization of parameters
int* p = new int[2];
int p_index=l;
int pivot = a[r];
//Loop through the array and check if a[i] is less than pivot
for(int i=l;i<r;i++){
if(a[i]<=pivot){
counter++;
swap(a[i],a[p_index]);
counter++;
p_index++;
}
}
swap(a[p_index],a[r]);
counter++;
p[0] = p_index;
p[1] = counter;
return p;
}
//Recurse algorithm for QuickSort
int QuickSort(int *a,int l,int r,int counter){
int count = counter;
if(l<r){
int *p = partion(a,l,r,count);
int p_index = p[0];
QuickSort(a,l,p_index-1,count);
QuickSort(a,p_index+1,r,count);
count = p[1];
}
return count;
}
int main(){
//int a[] = {7,2,1,6,8,5,3,4};
int a[] = {7,2,8};
int counter = QuickSort(a,0,2,0);
//Comparisions count
cout << "Number of comparisions performed = "<<counter<<endl;
//Printing the array
for(int i=0;i<3;i++)
cout << a[i]<< " ";
system("PAUSE");
return 0;
}
【问题讨论】:
-
交换不比较参数,无论比较结果是否为
true,比较计数器都应该上升。 -
添加一个
compare方法或带捕获的委托,并计算它被调用的频率
标签: c++ algorithm sorting quicksort