//归并排序 通过测试
public class MergeSortTest{
public static void mergeSort(int[] data,int low,int high){
if(low<high) {
int mid=(low+high)/2;
mergeSort(data,low,mid);
mergeSort(data,mid+1,high);
merge(data,low,mid,mid+1,high);
}
}
public static void merge(int[] data,int start1,int end1, int start2, int end2) {
int i=start1;
int j=start2;
int k=0;
int[] temp=new int[end2-start1+1];//辅助空间
while(i<=end1&&j<=end2){
if(data[i]>data[j])
temp[k++]=data[j++];
else
temp[k++]=data[i++];//保证稳定性
}
while(i<=end1)
temp[k++]=data[i++];
while(j<=end2)
temp[k++]=data[j++];
//将临时数组复制给原数组
k=start1;
for(int element:temp)
data[k++]=element;
}
//-----------------------------------------------------------------------------
public static void main (String args[]){
int x[]={9,8,7,6,5,4,3,2,1};
mergeSort(x,0,x.length-1);
for(int i=0;i<x.length;i++){
System.out.println(x[i]);
}
}
}