#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); }
使用递归的归并排序方法
时间: 2024-10-28 10:14:29