二分法找值就是类似于从这些有序的值中选中间的值 然后判断跟要找的值比较大小,判断是在中间值的左边还是右边,然后再从其中一边再找中间值取出来,以此类推。
二分法取值有个前提条件:数组有序不重复。
例如:
3,5,7,9,10,15,22,33,56,89取值
boolean found =false; int wz =-1; Scanner sc = new Scanner(System.in); int zhao = sc.nextInt(); int a[]= new int[]{3,5,7,9,10,15,22,33,56,89}; int xiao=0,da=9,zhong; while(xiao<=da) { zhong=(xiao+da)/2; if(a[zhong]==zhao) { found=true; wz= zhong; break; } else { if(a[zhong]<zhao) { xiao=zhong+1; } else { da=zhong-1; } } } if(found==false) { System.out.println("木找到"); } else { System.out.println("找到了"+" "+(wz+1)); }