- class Test
- {
- public static void main(String[] args)
- {
- int[] arr={12,6,72,34,36,7,6,5,8,2};
- int index=halfSearch(arr,2);
- System.out.println("index="+index);
- }
- public static int halfSearch(int[] arr,int key)
- {
- int min,max,mid;
- min=0;
- max = arr.length-1;
- mid = (max+min)/2;
-
- while (arr[mid]!=key)
- {
- if (key>arr[mid])
- min=mid+1;
- else if (key<arr[mid])
- max=mid-1;
-
- if(min>max)
- return -1;
- mid=(min+max)/2;
- }
- return mid;
- }
- }
复制代码 不知道错哪了 不管查哪个数都 是 index=-1 的结果。。。。 |