即:数组a[]; 对于i < j 且 a[i] > a[j],则称这是一个反序。
给定一个数组,要求写一个函数,计算出这个数组里所有反序的个数。
采用归并排序可以实现,时间复杂度为O(nlgn)源码如下:
void findRovatePair(int a[],int length,int *temp);
void merge(int a[],int low,int mid,int high,int *temp);
void mergeSort(int a[],int low,int high,int *temp);
void merge(int a[],int low,int mid,int high,int *temp)
{
int l=low,m=mid+1,k=0;
while(l<=mid && m<=high )
{
if(a[l]>a[m])
{
temp[k++]=a[m++];
pairs=pairs+mid-l+1;//在归并排序中增加了这个语句,记录反序对数
}
else
{
temp[k++]=a[l++];
}
}
while(l<=mid)
{
temp[k++]=a[l++];
}
while(m<=high)
{
temp[k++]=a[m++];
}
for(l=0;l<k;l++)
{
a[low+l]=temp[l];
}
}
void mergeSort(int a[],int low,int high,int *temp)
{
if(low<high)
{
int mid=(low +high)/2;
mergeSort(a,low,mid,temp);
mergeSort(a,mid+1,high,temp);
merge(a,low,mid,high,temp);
}
}
void findRovatePair(int a[],int n,int *temp)
{
mergeSort(a,0,n-1,temp);
cout<<"pairs:"<<pairs<<endl;
}