本帖最后由 邹海洋 于 2012-10-30 14:57 编辑
public class ZheBan1
{
//定义求值的方法
public static int halfSearch(int [] arr,int key)
{
int min = 0,max = arr.length-1,mid=0;
while (min<=max)
{
mid = (min+max)>>1;
if (key < arr[mid])
{
max = mid - 1;
}else if (key>arr[mid])
{
min = mid + 1;
}else
{
return mid;
}
//mid = (min + max)>>1; //此处如果注释掉,那么这个循环不就没法继续吗但是,结果却是对的,求解?
}
return -1;
}
//定义主函数
public static void main(String args[])
{
int score[]={2,3,5,7,9,23,25,35,56};
int num = halfSearch(score,56);
System.out.println(num);
}
} |
|