public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=(min+max)/2;
while (arr[mid]!=key)//楼主此处没有弄清循环条件
{
if (key<arr[mid])
max=mid-1;
else if(key>arr[mid])
min=mid+1;
mid=(min+max)/2;
}
return mid;
}
}
上面的while循环是当条件满足时就会一直循环,所以当你输入的值满足时也会进入循环,成了死循环。正确的程序我写在了下面。
class ArrDemo
{
public static void main(String[] args)
{
int[] arr={1,2,5,9,12,23,45,89};
int x=halfSearch(arr,4);
System.out.println(x);
}
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=(min+max)/2;
if(key<arr[0]||key>arr[arr.length-1])
{
System.out.println("值不存在!");
return -1;
}
while (arr[mid]!=key)
{
if (key<arr[mid])
max=mid-1;
else if(key>arr[mid])
min=mid+1;
mid=(min+max)/2;
}
return mid;
}
} |