//今天看了毕向东老师的Java基础视屏,有点问题不清楚。请大家帮忙看看,谢谢!
class ArrayTest
{
public static void main(String[] args)
{
int [] arr = new int[]{1,3,4,6,8,9,12};
int index = halfSearch(arr,30);
System.out.println("index="+index);//返回数组角标值
}
/*
折半查找。
*/
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length-1;
mid = (max+min)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min = mid +1;
else if (key<arr[mid])
max = mid-1;
if (min>max)//<<<<------问题就在这,为什么用min>max该判断能够判定key在数组中不存在呢?
return -1;
mid = (max+min)/2;
}
return mid;
}
}
|
|