gct 专业课考了个折半查找算法

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		int i = findKey(1,st.length);
		System.out.println(i);

	}
	private static int[] st  = {10,20,5,7,11,5,7,11};
	private static int key = 10;
	public static int findKey(int start,int end){
		int middle = (start+end)/2;
		int ret =0;
		if(st[middle-1] == key) return middle;		
		else{
			if(middle>start)
				ret = findKey(start,middle-1);
			if(ret==0){
				if(middle<end) ret = findKey(middle+1,end);
			}
			if(ret !=0) return ret;			
		}
		return 0;
		
	}

}

你可能感兴趣的:(算法)