C++ 如何在快速排序算法中计算比较的数量?
我有以下快速排序算法:C++ 如何在快速排序算法中计算比较的数量?,c++,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_
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;
}
int快速排序(int数据[]、大小、int和计数器)
//使用的图书馆设施:cstdlib
{
size\u t pivot\u index;//pivot元素的数组索引
size\u t n1;//枢轴元素之前的元素数
size\u t n2;//轴元素之后的元素数
如果(n>1)
{
//对数组进行分区,并设置透视索引。
分区(数据,n,pivot\u索引,计数器);
//计算子阵列的大小。
n1=枢轴指数;
n2=n-n1-1;
//递归调用现在将对子数组进行排序。
快速排序(数据、n1、计数器);
快速排序((数据+轴索引+1),n2,计数器);
}
返回计数器;
}
无效分区(整型数据[]、大小、大小和轴索引、整型和计数器){
int pivot=数据[0];
尺寸太大指数=1;
尺寸太小,指数=n-1;
虽然(索引太大)可能你的算法正在进行n^2/2
比较。快速排序的最坏情况是O(n^2)
,这是一些C*n^2
C
为0.5左右是完全有效的否?或者你有理由相信C
在这种情况下是1吗?