你把min max的值定义在了for循环内,就是局部变量只在for循环的{}内有效 所以不能返回min max的值因为获取不到。正确的代码如下
class Sort
{
public static void main(String[] args)
{
int[] arr = {2,4,5,7,8,19,32,45};
int x = halfSearch(arr,9);
System.out.println(x);
}
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length-1;
while (min<=max)
{
mid = (min+max)/2;
if (key>arr[mid])
{
min = mid+1;
}
else if (key<arr[mid])
{
max = mid-1;
}
else
return mid;
}
return min;
}
|