java实现一个简单的二分查找
public static int bsearch(int[] a, int n, int value) {//a是查找目标数组,n是数组长度,value是查找的值
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == value) {
return mid;
} else if (a[mid] < value) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
@Test
public void test1(){
int[] a={1,2,3,4,5,6,7,8,9};
int value=9;
System.out.println(bsearch(a,a.length,value));
}