class lianxi
{
public static int half(int[] arr,int key)
{
int min = 0,max=arr.length-1,mid;
while (min<=max)
{
mid=(max+min)/2;
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
else
return mid;
}
return -1;
}
public static void main(String[] args)
{
int[] arr={2,3,5,8,10,20};
int index =half(arr,22);
System.out.println("index="+index);
}
上面那个while判断min不是会一直小于等于max么 为什么要找的数不在数组中会输出-1?
|
|