/**
* 二分查找
*/
public class HalfSearch {
public static void main(String[] args) {
int[] a = new int[]{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
int searchNum = 18;
System.out.println("index=" + (bsearch(a, 11, searchNum) + 1));
}
public static int bsearch(int[] a, int n, int val) {
return bsearchInternally(a, 0, n - 1, val);
}
private static int bsearchInternally(int[] a, int low, int high, int value) {
if (low > high) return -1;
int mid= (low+high)/2;
if (a[mid] == value) {
return mid;
}
else if (a[mid] < value) {
return bsearchInternally(a, mid+1, high, value);
} else {
return bsearchInternally(a, low, mid-1, value); }
}
}