public void binarySearch(int value){
int low = 0;
int upper = nElements - 1;
int currtIn = (low+upper)/2;
while(true){
if(array[currtIn] == value){
System.out.println("find it :_"+currtIn+" "+array[currtIn]);
return;
}else if(array[currtIn] > value){//若当前值比关键字大,说明关键字在其前,upper要变为当前下标-1
upper = currtIn-1;
}else{
low = currtIn+1;
}
if(low>upper){
System.out.println("can`t find it :"+value);
return;
}
currtIn = (low+upper)/2;
}
}
递归实现:
public void recBinarySearch(int value,int low,int upper){
int current = (low+upper)/2;
if(array[current] == value){
System.out.println("find it:"+current+" value:"+array[current]);
return;
}else if(low > upper){
System.out.println("can`t find it");
}else{
if(value > array[current]){
recBinarySearch(value, current+1,upper);
}else{
recBinarySearch(value, low, current-1);
}
}
}