public static void main(String[] args)
{// TODO Auto-generated method stub//
int aa[]={4,2,6,7,9,10,5,4,8,1};
int aa[]={4,2,6,7,9,1};
print(aa);
System.out.println("inversion num: "+INVERSION1(aa));
System.out.println("inversion num: "+MERGE_SORT(aa, 0, aa.length-1));
print(aa);}
static int INVERSION1(int []a){
int num=0;
for(int i=0;i<a.length-1;i++)
for(int j=i+1;j<a.length;j++){
if(a[j]<a[i])num++;}
return num;}
static int MERGE_SORT(int []a,int i,int j){
if(j>i){
int num=0;int k=(j+i)/2;
int s1=MERGE_SORT(a, i, k);
int s2=MERGE_SORT(a, k+1, j);
//a[i,k,j]
int n1=k-i+1;
int n2=j-k;
int L[]=new int[n1+1];
int R[]=new int[n2+1];for(int m=0;m<n1;m++)L[m]=a[i+m];for(int n=0;n<n2;n++){R[n]=a[k+1+n]; }L[n1]=999;R[n2]=999;int p=0,q=0;
for(int t=i;t<=j;t++){
if(L[p]>R[q]){
a[t]=R[q];
q++;
num+=n1-p;
//当L>R的时候 n1-p均比R[q]大
}else{
a[t]=L[p];p++;
}
}
return num+s1+s2;
}
return 0;
}
最坏情况运行时间为 O(nlgn)
C++版:
#include<iostream> using namespace std; #define MAX 0x7FFFFFFF int Merge(int array[],int start,int mid,int end){ int num=0; int n1=mid-start+1; int n2=end-mid; int *left=new int[n1+1]; int *right=new int[n2+1]; int i,k,j; for (i=0;i<n1;i++) left[i]=array[start+i]; for (j=0;j<n2;j++) right[j]=array[mid+1+j]; left[n1]=MAX; right[n2]=MAX; for ( k=start,i=0,j=0;k<=end;k++) { if (left[i]<=right[j]){ array[k]=left[i]; ++i; } else{ num+=n1-i; array[k]=right[j]; ++j; } } delete []left; delete []right; return num; } int MergeSort(int array[],int start,int end){ if (start<end) { int mid=(start+end)/2; int s1=MergeSort(array,start,mid); int s2=MergeSort(array,mid+1,end); int num=Merge(array,start,mid,end); return s1+s2+num; } return 0; } int main(){ int A[]={16,202,100,301,138,8,1}; int num=MergeSort(A,0,6); for (int i=0;i<=6;i++) { cout<<A[i]<<" "; } cout<<endl<<"逆序数个数:"<<num<<endl; }