C++求数组中的逆序对

来源:互联网 发布:网络电视提示解压失败 编辑:程序博客网 时间:2024/06/06 02:42

C++求数组中的逆序对。

如果在数组中的两个数字如果前面的一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数


#include<iostream>

using namespace std;
//归并排序统计逆序对
int merge(int num[],int start,int middle,int end,int*temp)
{
int k=0,i=start,j=middle+1,count=0;
for(;i<=middle&&j<=end;)
{
if(num[i]>num[j])
{
temp[k++]=num[i++];//按照的是从大到小的顺序排
count+=end-j+1;//如果第一个子数组的数字大于第二个子数组中的数字,则构成逆序数目等于第二个子数组中剩余数字的个数
}
else
temp[k++]=num[j++];
}
while(i<=middle)
temp[k++]=num[i++];
while(j<=end)
temp[k++]=num[j++];
for(int index=0;index<k;index++)
num[start+index]=temp[index];//注意这里在跟新num中相应位置排序的时候不能写为index,一定要写为start+index
return count;
}
int InversePairs(int num[],int start,int end,int* temp)//这个其实就是改编自归并排序的mergesort函数,基本都是一样的
{
int count=0;
if(num==NULL||start>end||end<0||start<0)
return 0;
if(start<end)
{
int middle=(start+end)/2;
count+=InversePairs(num,start,middle,temp);//左半部分逆序对数量
count+=InversePairs(num,middle+1,end,temp);//右半部分逆序对数量
count+=merge(num,start,middle,end,temp);//合并两个部分时产生的逆序对数量,并把之前计算出的逆序对数量累加
}
return count;
}




int main()
{
int num[]={7,5,6,4};
int length=sizeof(num)/sizeof(int);
int *temp=new int[length];
int result=InversePairs(num,0,length-1,temp);
cout<<result<<endl;
delete [] temp;
return 0;
}
0 0
原创粉丝点击