思路:
利用归并排序的思想,一边归并排序,一边求逆序对。时间复杂度为O(n log n)
步骤:递归实现
(1)现将数组拆分成2两部分,统计出子数组内部的逆序对left、right;
(2)然后再统计出两个相邻子数组之间的逆序对count。在统计过程中,对数组进行排序。(归并过程)
(3)最终的逆序对个数=left+right+count;
int inversePairs( int *data, in length)
{
if(data==NULL || length<0)
return 0;
int *copy=new int[length];
for(int i=0;i<length;i++)
copy[i]=data[i];
int count=inversePairsCore(data, copy, 0, length-1);
delete [] copy;
return count;
}
int inverseParisCore(int *data, int *copy, start, end)
{
//递归出口
if(start==end)
{
copy[start]=data[start];
return 0;
}
int length=(end-start)/2;
int left=inversePairsCore(data, copy, start, start+length);//递归调用
int right=inversePairsCore(data, copy, start+length+1, end);//递归调用
//归并排序,且求左右子数组间逆序对
int i=start+length;//指向左子数组的最后位置
int j=end; //指向右子数组的最后位置
int indexCopy=end;
int count=0;
while(i>=start && j>=start+length+1)
{
if( data[i]> data[j] )
{
copy[indexCopy--]=data[i--];
count+= ( j-(start+length+1)+1 );
}
else
copy[indexCopy--]=data[j--];
}
//拷贝剩余数组部分
for(; i>=0; i--)
copy[indexCopy--]=data[i];
for(; j>=start+length+1; j--)
copy[indexCopy--]= data[j];
return count+left+right;
}