java基础之二分查找
时间:2020-08-11 00:26:19
收藏:0
阅读:77
一、
public class BinarySeachTest {
public static void main(String[] args) {
int[] arr = new int[]{22,54,88,97,105,112};
System.out.println(binarySeach(arr, 112));
}
/**
*
* @return 返回传入的value在数组位置
*/
public static int binarySeach(int[] num,int value){
int start=0; //数组的开始下标
int end =num.length-1; //数组的结尾下标
while(start<=end){
int middle = (start+end)/2; //中间位置
if(num[middle]>value){
end=middle-1;
}else if(num[middle]<value){
start=middle+1;
}else {
return middle;
}
}
return -1;
}
}
评论(0)