二分法查找
/**
* 二分法查找 找不到返回-1
* @author yangzi
*
*/
public class TwoFind {
public static int twoFind(int ia, int[] arr, int left, int right) {
if (left > right) {
return -1;
}
if (arr[(left + right) / 2] == ia) {
return (left + right) / 2;
}
if (arr[(left + right) / 2] < ia) {
return twoFind(ia, arr, (left + right) / 2 + 1, right);
}
if (arr[(left + right) / 2] > ia) {
return twoFind(ia, arr, left, (left + right) / 2 - 1);
}
return -1;
}
public static void main(String[] args) {
// 下标 0 7 8 15
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
int ia = 16;
int left = 0;
int right = arr.length - 1;
// 调用
System.out.println(twoFind(ia, arr, left, right));
}
}