张帅 发表于 2011-12-16 21:09
我调试了下,发现永远都返回 -1;
正常的,
测试代码:- class Test
- {
- public static void main(String[] args)
- {
- int [] a ={1,2,3,5,7,8,9};
- System.out.println(halfSearch(a,8));
- System.out.println(halfSearch(a,6));
-
- }
- public static int halfSearch(int[] arr,int key)
- {
- int min,max,mid;
- min = 0;
- max = arr.length-1;
- while(min<=max){
- mid = (min+max)>>1;
- if(key>arr[mid]){
- min = mid +1;
- }else if(key<arr[mid]){
- max = mid - 1;
- }else{
- return mid;
- }
- }
- return -1;
- }
- }
复制代码 测试结果: |