bottomUpSort 我想呢,很久終於在相通呢,如今貼在這裏,好記性不如爛筆頭。 歸併 排序java
<!-- lang: java --> package chapter1; public class MERGE { //0<=p<=q<r<=A.length public void merge(int[] A,int p,int q,int r){ int s=p,t=q+1,k=p; int[] B = A.clone(); while(s<=q && t<=r){ if(A[s]<=A[t]){ B[k]=A[s]; s++; } else{ B[k]=A[t]; t++; } k++; } if(s==(q+1)){ while(k<=r){ B[k]=A[t]; k++;t++; } } else{ while(k<=r){ B[k]=A[s]; k++; s++; } } for(int i=p;i<=r;i++) { A[i]=B[i]; } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] array = {2,3,66,7,11,13,45,57}; MERGE merge=new MERGE(); merge.merge(array, 0, 3, 4); for(int i:array) System.out.print(i+" "); } }
置底向下 排序數組
<!-- lang: java --> package chapter1; public class BOTTOMUPSORT { public void bottomUpSort(int[] A){ int t=1; while(t<A.length){ int s=t; //s爲比較數組的長度 t=2*s;//比較塊 int i=0; //比較數組的長度 依次遞增 while(i+t < A.length){ new MERGE().merge(A, i, i+s-1,i+t-1); i=i+t; } System.out.println("i+s = "+(i+s)); if(i+s<A.length){ new MERGE().merge(A, i, i+s-1, A.length-1); } } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] array = {6,10,9,5,3,11,4,8,1,2,7,0}; BOTTOMUPSORT bus = new BOTTOMUPSORT(); bus.bottomUpSort(array); for(int i : array){ System.out.print(i+" "); } } }