#include<iostream>
using namespace std;
void MergeSortAndCount(int start,int end,int a[],int tmp[],int& count)
{
if(start>=end)
{
return;
}
int mid=(start+end)/2;
MergeSortAndCount(start,mid,a,tmp,count);
MergeSortAndCount(mid+1,end,a,tmp,count);
int i=start,j=mid+1,k=start;
while(i<=mid&&j<=end)
{
if(a[i]>=a[j])
{
tmp[k++]=a[j++];
}
else
{
tmp[k++]=a[i++];
}
}
while(i<=mid)
{
tmp[k++]=a[i++];
}
while(j<=end)
{
tmp[k++]=a[j++];
}
i=start;
j=mid+1;
while(i<=mid&&j<=end)
{
if(a[i]>a[j])
{
count+=mid+1-i;
j++;
}
else
{
i++;
}
}
for(i=start;i<=end;i++)
{
a[i]=tmp[i];
}
}
int main()
{
int Arr[]={11,3,45,22,7,9,23,18,27,8,13};
int size=sizeof(Arr)/sizeof(int);
for(int i=0;i<size;i++)
{
cout<<Arr[i]<<" ";
}
cout<<endl;
int temp[size],count=0;
MergeSortAndCount(0,size-1,Arr,temp,count);
for(int i=0;i<size;i++)
{
cout<<Arr[i]<<" ";
}
cout<<endl;
cout<<count;
return 0;
}
求逆序对的个数
最新推荐文章于 2023-04-07 22:10:26 发布