JAva二分検索実装

902 ワード



public class BinaryChop {
	private int a[];
	private int nElements ;
	
	public int find(int searchKey){
		int lower = 0;
		int upper = nElements -1;
		int curIn;
		while(true){
			curIn = (lower + upper)/2;
			if(a[curIn] == searchKey){
				return curIn;
			}else if(lower > upper)
				return nElements;
			else{
				if(a[curIn] < searchKey)
					lower = curIn +1;
				else
					upper = curIn -1;
			}
		} 
		
	}
	public BinaryChop(int a[]){
		this.a = a;
		this.nElements = a.length;
	}
	public static void main(String[] args) {
		int a[] = new int[100];
		for(int i= 0;i <100;i++){
			a[i] = i+1;
		}
		System.out.println(new BinaryChop(a).find(22));
	}

}