java 實現二分查找法

package offer08;
/**
 * 二分查找,適合已經排好序的數組
 * 【二分查找要求】:1.必須採用順序存儲結構 2.必須按關鍵字大小有序排列。
 * @author tcj
 *
 */
public class BinarySearch {
	
	//a是一個已經排好序的數組,這裏假設爲升序
	//遞歸實現
	public static int search(int x,int[] a,int start,int end){
		int middle = (end+start)/2;
		if(x < a[start] || x > a[end] || start > end){
			return -1;
		}
		if(x < a[middle]){
			return search(x,a,start,middle-1);
		}else if(x == a[middle]){
			return middle;
		}
		else{
			return search(x,a,middle+1,end);
		}
	}
	
	//循環實現
	public static int search02(int x,int[] a){
		int low = 0;
		int high = a.length - 1;
		while(low <= high){
			int middle = (high + low)/2;
			if(x == a[middle]){
				return middle;
			}else if(x < a[middle]){
				high = middle - 1;
			}else{
				low = middle + 1;
			}
		}
		return -1;
	}
	public static void main(String[] args){
		int[] a = {1,2,3,4,5};
		System.out.println(search(2,a,0,4));
		//測試非遞歸
		System.out.println(search02(5,a));
		
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章