当查找的数不存在时怎么出现错误啦!!
- Java code
//二分查找class SecondFind{ public static void main(String[] args) { //定义数组 int [] data=new int[]{2,3,4,5,6,7,8,9}; int index=getIndex(data,77); System.out.print("index="+index); } public static int getIndex(int []arr,int num){ int min=0,max=arr.length-1; int mid=(min+max)/2; while(arr[max]>=arr[min]){ mid=(min+max)/2; if(num>arr[mid]) min=mid+1; else if (num<arr[mid]) max=mid-1; else return mid; } return -1; } }
------解决方案--------------------
while(arr[max]>=arr[min])
-->
while (max >= min)