1. 程式人生 > >二分查詢java實現

二分查詢java實現

二分查詢java實現

public class BinarySearch {
	public static void main(String[] args) {
		int [] a={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
		BSearch(a,100);
	}
	private static void BSearch(int [] a ,int i) {
		int low,high,mid;
		low=0;
		high=a.length -1;
		mid=low+(high-low)/2;
		while(low<high){
			if(a[mid]==i){
				System.out.println("查詢的位置為"+mid);
				break;
			}else if(a[mid]<i){
				low=mid+1;
				mid=low+(high-low)/2;
			}else{
				high=mid-1;
				mid=low+(high-low)/2;
			}
		}
		if(a[mid]!=i){
			System.out.println(i+"沒有在陣列之中");
		}
	}
}