二分法有前提:数组一定要有序。
public class BinarySearch {
public static void main(String[] args) {
int [] arr = { 1,3,5,7,9 };
System.out.println(search(arr, 0, arr.length-1, 70));
}
public static int search( int [] arr, int left, int right, int value ) {
int mid = (left + right)/2;
int midVal = arr[mid];
//数据都比对完成时,退出
if( left > right) {
return -1;
}
if( value > midVal ) {
return search(arr, mid+1, right, value);
}else if( value < midVal) {
return search(arr, left, mid-1, value);
}else {
return mid;
}
}
}