求数组的逆序对个数。如【3,5,1,15】,共有(3,1),(5,1)两对,逆序对个数为2;
1:显然这个可以用穷举的方法去做,类似于直接选择排序,复杂度n^2.
2:也可以用归并的方式去做,思路是:归并时,假设两个子数组已经排序,数组1在前,当前元素为x,数组2在后,当前元素为y,如果y
3:还可以用树状数组来做。每次插入时检查比他大的元素的个数。以下是思路1、思路2和思路3的代码:
#include
#include
#include
using namespace std;
void merge(int *p, int m, int mid, int n, int *ptmp);
int s = 0;
void merge_sort(int *p, int l, int r, int *ptmp)
{
if (l >= r)
return;
int m = l + (r - l) / 2;
merge_sort(p, l, m, ptmp);
merge_sort(p, m + 1, r, ptmp);
merge(p, l, m, r, ptmp);
copy(ptmp+l, ptmp + r+1, p + l);
}
void merge(int *p, int m, int mid, int n, int *ptmp)
{
int x = m;
int y = mid + 1;
int i = m;
while(x <= mid && y <= n)
{
if(p[x] <= p[y])
ptmp[i++] = p[x++];
else
{
ptmp[i++] = p[y++];
s += (mid - x + 1); // 归并排序上加这么一句就行
}
}
while(x <= mid) ptmp[i++] = p[x++];
while(y <= n) ptmp[i++] = p[y++];
}
int lowbit(int x)
{
return x & -x;
}
void modify(int *ap, int n, int pos, int v)
{
int i;
for (i=pos; i<= n; i += lowbit(i))
ap[i] += v;
}
int gsum(int *ap, int n, int pos)
{
int i;
int s = 0;
for (i=pos; i>=1; i -= lowbit(i) )
s += ap[i];
return s;
}
int main()
{
int a[] = {3,5,1,15,67,23,23,87,89,2};
// 1 // 暴力法计算逆序对
int x = 0;
int i, j;
for (i=0; i<10-1; i++)
for(j=i+1; j<10; j++)
if (a[i] > a[j])
x++;
cout<<"1.暴力法计算逆序对: "<(cout, " "));
cout<(cout, " "));
//cout<
输出:
1.暴力法计算逆序对: 12
1 2 3 5 15 23 23 67 87 89
2.归并法计算逆序对: 12
3.树状数组法: 12