import java.util.Scanner; public class shuzu { public static void main(String[] args) { int[] arr= {3, 6, 9, 23, 34, 45, 56, 67}; System.out.println("请输入一个查找的数据:"); Scanner scanner = new Scanner(System.in); try{ int num=scanner.nextInt(); int start_index=-1; int end_index=arr.length; int mid=(start_index+end_index)/2; System.out.println(start_index); System.out.println(end_index); System.out.println(mid); while(arr[mid]!=num){ if(arr[mid]<num){ start_index=mid+1; }else{ end_index=mid-1; } if(start_index>=end_index){ break; } mid=(start_index+end_index)/2; System.out.println(mid); System.out.println(start_index); System.out.println(end_index); } if(arr[mid]==num) { System.out.println("元素找到,位置:"+mid); }else{ System.out.println("元素在此数组中不存在"); } }catch(Exception e){ System.out.println("你输入的数字不合法"); } } }
运行结果: