# 寻找异序对算法

package test;

public class testmerge{

public static void main(String[] args) {
int[] data = new int[] { 8,9,2,3,5,7};
print(data);
int result= 0;
result=sort(data,0,5);
System.out.println(“排序后的数组：”);
System.out.println(“final result:”+result);
print(data);
}

public static int sort(int[] data, int left, int right) {
int l,r,mid,sum,center;
if (left >= right)
return 0;
// 找出中间索引
center = (left + right) / 2;
// 对左边数组进行递归
l= sort(data, left, center);
// 对右边数组进行递归
r=sort(data, center + 1, right);
// 合并
mid= merge(data, left, center, right);
sum=l+r+mid;
return sum;
}

public static int  merge(int [] a,int start,int mid,int end){
int n1=mid-start+1;
int n2=end-mid;
int count=0;
int [] left=new int[n1];
int [] right=new int[n2];
int i,j;
for(i=0;i<n1;i++){
left[i]=a[start+i];
}

for(j=0;j<n2;j++){
right[j]=a[mid+j+1];
}

i=0;j=0;
int k=start;
while(i<n1&&j<n2){
if(left[i]<right[j]){
a[k++]=left[i++];
}
else{
a[k++]=right[j++];
count=count+n1-i;
}
}

while(i<n1){
a[k++]=left[i++];
}

while(j<n2){
a[k++]=right[j++];
}
System.out.println(“count is “+count);
return count;
}

public static void print(int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + “\t”);
}
System.out.println();
}

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。