public static void main(String[] args)
{
int[] arr={1,2,3,5,6,7,8,9,56};
int index=halfSearch(arr,5);
System.out.println("index="+index);
}
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=(min+max)/2;
if (arr[mid]!=key) //此处为何用while而不能用if??
{
if (key>arr[mid])
min=mid+1;
else if (key<arr[mid])
max=mid-1;
mid=(max+min)/2;
}
return mid;
}
|
|