你的代码没有错
class ArrDemo_2
{
public static void main(String[] args)
{
int [] arr ={1,2,3,4,5,6};
halfSearch(arr,31);//是你在这里定义的31出了问题,是因为你定义 int [] arr ={1,2,3,4,5,6};没有31这个数,你可以传个3试试
}
public static void halfSearch(int [] arr,int key)
{
int min = 0,max = arr.length,mid;
mid = (min +max)/2;
while (arr[mid]!=key)
{
if (arr[mid]>key)
{
max = mid-1;
mid = (min +max)/2;
}
else if (arr[mid]<key)
{
min = mid+1;
mid = (min +max)/2;
}
if (min>max)
mid=-1;
}
System.out.println(mid);
}
}
|