二分法直接与中间值进行比较,如果正确直接返回。如果小于中间值在前半部分求中间值进相比较。大则相反。 测试如下图:
public class Two { public static void main(String[] args) { int[] number = {1, 5, 6, 9, 10, 15}; int num = 9; guessNum(number, num); } public static void guessNum(int[] num, int res) { int start = 0; //开始的索引 int end = num.length - 1; //数组结束的索引 while (start<=end){ //循环到索引开始等于结束为止 int mid = (end + start) / 2; //每次循环重新计算中间索引并取整 System.out.println("mid-----------"+mid); if (res == num[mid]) { //如果中间索引值相等进行结果显示并终止循环 System.out.println(num[mid]); System.out.println("guess success!"); break; } else if (res < num[mid]) { //如果值比中间值小则重新对结尾值赋值 end = mid - 1; System.out.println("end-----------"+end); }else { //如果值比中间值大则重新对开始值赋值 start=mid+1; System.out.println("end-----------"+start); } } } }