1、思想:找中间的数,变换左右边界值
2、编程要点:设置 l<=r 作为作为循环判断标志
3、代码
import java.util.*;
/**
* 1、找到
* 2、没找到
*/
public class Main {
public static void main(String[] args) {
int[] arr = new int[]{1, 4, 7, 9, 12, 15, 17, 25, 33};
int target = 1;
System.out.println(bsearch( arr, target));
}
private static boolean bsearch(int[] arr, int target) {
int l = 0;
int r = arr.length – 1;
int m =0;
boolean found = false;
while (l <= r){
m = (l + r) / 2;
if (arr[m] == target){
System.out.println(m);
return found = true;
}else {
if (arr[m] > target){
r = m – 1;
}else {
l = m + 1;
}
}
}
return false;
}
}