为什么把2,5,19定义进去打印的结果却是-1。这个数组明明有这几个元素啊。谢谢
*/
class ArrayTest5
{
public static void main(String[] args)
{
int[] arr = {2,4,5,7,19,32,45};
int index = halfSearch_2(arr,5); //2,5,19输出为-1
System.out.println("index="+index);
}
public static int halfSearch_2(int[] arr,int key)
{
int min = 0,max = arr.length-1,mid;
while(min<max)
{
mid = (max+min)>>1; // >>1表示除于2(三位运算符)
if(key>arr[mid])
min = mid+1;
else if(key<arr[mid])
max = mid-1;
else
return mid;
}
return -1;
}
} |
|