赞
踩
public class BinarySearch { public static void main(String[] args) { int[] bs ={1,3,5,7,9,13,17,20,33,37}; int low=0,mid; int high=bs.length-1; int m=10; //需要找的数 int count=0; //比较的次数 while(low<=high) { mid=(low+high)/2; if(m<bs[mid]) { high=mid-1; //注意!!high=mid-1,以前忘了 count++; } else if (m>bs[mid]) { low= mid+1; //注意!!low= mid+1,以前忘了 count++; } else { count++; System.out.println("找到了,下标是" + mid + "比较了" + count); break; } } if(low>high) { System.out.println("未找到"+"比较了" + count); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。