public class Merge_Sort { public static void merge(int a[],int n){ int source; //合并之前数组的大小 int target=1;//合并之后数组的大小 int index;//合并的数组的起始位置 while (target < n){ //如果合并之后的数组长度没有超过总的数组长度 source = target; //本次合并的数组的长度等于上次两个数组合并之后的长度 target = source * 2; //本次合并之后的数组的长度等于合并之前的数组的长度的两倍 index = 0; //数组的起始位置 while((index + target) < n){//如果数组的起始位置加上合并后的长度比数组的长度短 则进行合并 sort(a,index,index+source,index+target); //合并 index += target;//起始位置后移 } if((index + source) < n){ //如果最后一段 无法分成均等的两组 sort(a,index,index+source,n); //合并 } } } public static void sort(int a[],int index,int boundary1, int boundary2){ int i = index; int j = boundary1; int temp[] = new int[boundary2-index]; int k = 0; while(i< boundary1 && j < boundary2){ if(a[i] < a[j]){ temp[k++] = a[i++]; }else{ temp[k++] = a[j++]; } } while(i < boundary1){ temp[k++] = a[i++]; } while(j < boundary2){ temp[k++] = a[j++]; } for(int m = 0; m < temp.length; m++){ a[index+m] = temp[m]; } } public static void main(String[] args){ int[] a = {8,5,3,9,11,6,4,1,10,7,2}; merge(a,a.length); for(int i : a){ System.out.println(i); } } }