Merge and BottomUpSort

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+" ");
		}
	}
}
相关文章
相关标签/搜索