c++ - 如何计算快速排序算法中的比较次数?
问题描述
我有以下快速排序算法:
int quicksort(int data[], size_t n, int &counter)
// Library facilities used: cstdlib
{
size_t pivot_index; // Array index for the pivot element
size_t n1; // Number of elements before the pivot element
size_t n2; // Number of elements after the pivot element
if (n > 1)
{
// Partition the array, and set the pivot index.
partition(data, n, pivot_index, counter);
// Compute the sizes of the subarrays.
n1 = pivot_index;
n2 = n - n1 - 1;
// Recursive calls will now sort the subarrays.
quicksort(data, n1, counter);
quicksort((data + pivot_index + 1), n2, counter);
}
return counter;
}
void partition(int data[], size_t n, size_t& pivot_index, int &counter){
int pivot = data[0];
size_t too_big_index = 1;
size_t too_small_index = n - 1;
while (too_big_index <= too_small_index)
{
while (++counter && (too_big_index < n) && (data[too_big_index] <= pivot)) too_big_index++;
while (++counter && data[too_small_index] > pivot ) too_small_index--;
counter++;
if (too_big_index < too_small_index) swap(data[too_big_index], data[too_small_index]);
};
pivot_index = too_small_index;
data[0] = data[pivot_index];
data[pivot_index] = pivot;
}
我在分区函数中添加了三个计数器增量,但是当使用 8000 个元素的排序数组时,计数器的值是 32019997,我使用的是最左边元素的枢轴(我知道这给了我一个就排序数组而言是最坏的情况),除非我不正确,否则最坏的情况不应该是 n^2 即 64000000 吗?所以我认为我计算比较的方式是错误的,但我不确定如何。
解决方案
推荐阅读
- javascript - 引导模式弹出窗口不会关闭
- spring - 如何从 Thymeleaf 表单中选择对象?
- javascript - AngularJS 和 Electron:无法在 Electron 中运行 AngularJS 应用程序
- javascript - Javascript 在按键上启动加载器并在绘制 SVG 时停止
- c# - c#datagridviewImageColumn无法显示来自url的图片
- java - 什么时候为映射 servlet 加载 web.xml 文件?
- dart - Angular Dart 材料下拉选择中的选择给出错误
- java - Spring Security:检查 Freemarker 模板中的用户角色
- python - 树莓派上的python3
- c++ - (C++) 将对象向量传递给构造函数