您的位置:首页 > Web前端

剑指offer第36题 求逆序数

2015-08-08 11:39 260 查看
#include<iostream>
using namespace std;

int Merge(int *list,int*copy,int s1,int s2,int end)
{
int i=s1;
int j=s2;
int k=s1;
int num=0;
for(int k=s1;k<=end;k++)
copy[k]=list[k];
while(i<=s2-1&&j<=end)
{
if(copy[i]>copy[j])
{
num=num+s2-1-i+1;
list[k]=copy[j];
j++;
k++;
}
else
{
list[k]=copy[i];
i++;
k++;
}
}
while(i<=s2-1)
{
list[k]=copy[i];
i++;
k++;
}
while(j<=end)
{
list[k]=copy[j];
j++;
k++;
}
return num;
}

int InverseCore(int *list,int *copy,int start,int end)
{
if(start==end)
return 0;
if(start<end)
{
int mid=(start+end)/2;
int left=InverseCore(list,copy,start,mid);
int right=InverseCore(list,copy,mid+1,end);
int m=Merge(list,copy,start,mid+1,end);
return left+right+m;
}
}
int InversePairs(int *list,int length)
{
if(list==NULL||length<0)
return 0;
int*copy=new int[length];//copy是辅助空间,作为参数传下去
int count=InverseCore(list,copy,0,length-1);
delete[]copy;
copy=NULL;
return count;
}

int main()
{
int a[1000];
int c;
int i=0;
while(cin>>c)
{
a[i]=c;
i++;
if(cin.get()=='\n')
break;
}
cout<<InversePairs(a,i);
}


使用递归的归并排序方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: