package com.atguigu;public class Main { public static void main(String[] args) { //二分法查找 //前提:所查找的数组必须有序 int[] arr=new int[]{-98,-34,2,34,54,66,79,105,210,333}; int dest=-3; int head=0;//初始的首索引 int end=arr.length-1; boolean isFlag=true; while(head<=end){ int middle=(head+end)/2; if(dest==arr[middle]){ System.out.println("找到指定的元素,位置为"+middle); isFlag=false; break; }else if(arr[middle]>dest){ end=middle-1; }else{ head=middle+1; } } if(isFlag){ System.out.println("很遗憾,没有找到"); } }}
来源:https://www.cnblogs.com/helloworld0903/p/11456552.html