【发布时间】:2018-05-30 17:38:52
【问题描述】:
我需要计算在合并排序期间发生了多少交换和比较,我认为我的比较数计数很好,只是由于递归,我得到的数字与我的数组长度一样多,不知何故我需要将这些数字存储到合并中的变量中排序功能?也很想知道如何计算总掉期
void merge(double arr[], int l, int m, int r)
{
int counter = 0;//number of comparisons
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int cc;
/* create temp arrays */
double L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
counter++;
}
cout << counter << endl;
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(double arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
【问题讨论】:
-
如果你想搜索它,它通常被称为计数反转(而不是交换)。您可以在合并期间对它们进行计数,假设您返回并求和反转计数。
-
double L[n1], R[n2];-- 这不是有效的 C++。 C++ 中的数组必须使用编译时常量声明,而不是变量。其次,您可以轻松地将整个代码放在一个类中,并拥有一个名为swapCount的成员变量,该变量会递增,而不是本地的counter变量。
标签: c++ algorithm sorting merge