2009-10-11 11:00:30 一个用Java实现的非递归合并排序(自底向上) public class UnRecursionMergeSort { static void MergeSort(int A[],int n){ int[] B = new int[n];//先分配一个长度跟A一样大的数组B int s = 1;//子序列长度,初始为1 while(s<n){ MergePass(A,B,s,n);//从A[]归并到B[] s+=s;//子序列长度加倍 MergePass(B,A,s,n);//从B[]归并到A[] s+=s;//子序列长度加倍 } } static void MergePass(int A[],int B[],int s,int n){ int i = 0; while(i<=n-2*s){//两两归并 Merge(A,B,i,i+s-1,i+2*s-1); i = i+2*s; } if(i+s<n){//归并最后两个序列 Merge(A,B,i,i+s-1,n-1); } else{//若最后只剩下单个序列 for(int j=i;j<=n-1;j++){ B[j] = A[j]; } } } static void Merge(int A[],int B[],int low,int mid,int high){ int i = low; int j = mid+1; int k = low; while((i<=mid)&&(j<=high)){ if(A[i]<=A[j]){ B[k++] = A[i++]; } else{ B[k++] = A[j++]; } } while(i<=mid){ B[k++] = A[i++]; } while(j<=high){ B[k++] = A[j++]; } } public static void main(String[] args) { int A[] = {78,102,90,8,7,6,5,40,3,11,1}; System.out.println("排序前,数组为:"); for(int i=0;i<A.length;i++){ System.out.print(A[i]+" "); } System.out.println(); MergeSort(A,A.length); System.out.println("排序后,数组为:"); for(int i=0;i<A.length;i++){ System.out.print(A[i]+" "); } } }