public class ErFenChaZhao {
//这个查找方法需要数据排列的很整齐,不断折半,缩小范围
/**
* 二分查找,返回索引值,如果没有找到返回-1 数组按照从小到大排列
*/
public static int binary_search(int [] arr,int len,int value){
if(arr==null||arr.length==0){
return -1;
}
int start = 0;
int end = len-1;
while(start<=end){
int middle= (start+end)/2;
if(arr[middle]==value){
return middle;
}else if(arr[middle]<value){
start=middle+1;
}else if(arr[middle]>value){
end = middle-1;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int a =binary_search(arr, 10, 8);
System.out.println(a);
}
}