#include <iostream>
using namespace std;
int merge(int A[], int p, int q, int r);
int merge_sort(int A[], int p, int r);
void main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << merge_sort(a, 0, 17) << endl;
system("pause");
}
int merge(int A[], int p, int q, int r) {
int i, j, k, inversions = 0;
int n1 = q - p + 1;
int n2 = r - q;
int *L = new int[n1];
int *R = new int[n2];
for (i = 0; i < n1; i++) L[i] = A[p + i];
for (j = 0; j < n2; j++) R[j] = A[q + j + 1];
for (i = 0, j = 0, k = p; k <= r; k++) {
if (i == n1) {
A[k] = R[j++];
}
else if (j == n2) {
A[k] = L[i++];
}
else if (L[i] <= R[j]) {
A[k] = L[i++];
}
else {
A[k] = R[j++];
inversions += n1 - i; //L比R小,计做一次逆序
//这里巧妙地利用了一个前提条件,LR都是有序的
}
}
return inversions;
}
int merge_sort(int A[], int p, int r) {
if (p < r) {
int inversions = 0;
int q = (p + r) / 2;
inversions += merge_sort(A, p, q);
inversions += merge_sort(A, q + 1, r);
inversions += merge(A, p, q, r);
return inversions;
}
else {
return 0;
}
}
《算法导论》6、计算一个数组中逆序数的个数(C++,使用合并排序改编)
最新推荐文章于 2021-10-21 23:50:12 发布