1. 程式人生 > >用Java泛型實現折半插入排序

用Java泛型實現折半插入排序

package ch10;

/**
 * successful-折半插入排序
 * @author songjie
 *
 */
public class BinaryInsertSort {
	public static <T extends Comparable> boolean binaryInsertSort(T[] t){
		if(t==null || t.length <= 1) return true;
		
		for(int i=1 ; i<=t.length-1 ; i++){
			T temp  = t[i];
			int low = 0;
			int high = i-1;
			
			while(low <= high){//此次迴圈之後,low = high+1
				int mid = (low+high)/2;
				if(temp.compareTo(t[mid]) > 0) low = mid + 1;
				else high = mid - 1;
			}
			for(int j=i-1 ; j>=low ; j--){
				t[j+1] = t[j];
			}
			t[low] = temp;
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		Integer[] arr = new Integer[]{3,5,7,1,3,4};
		BinaryInsertSort.<Integer>binaryInsertSort(arr);
		for(int i : arr){
			System.out.println(i);
		}
	}
}