int arr[]=new int[]{4,25,10};
Array.sort(arr);
int index=Arrays.binarySearch(arr,0,1,8);上面代码index为何等于-2?8不是应该在10的前面吗?10的索引值不是1吗?我觉得index的值应该是-1

解决方案 »

  1.   

    你自己先看看Arrays.binarySearch的源代码,看看这个方法到底是用来做什么的。
      

  2.   

    binarySearch
    这个方法只适合在有序数组中操作。
      

  3.   

    static int  binarySearch(byte[] a, byte key)
              Searches the specified array of bytes for the specified value using the binary search algorithm.
    static int  binarySearch(char[] a, char key)
              Searches the specified array of chars for the specified value using the binary search algorithm.
    static int  binarySearch(double[] a, double key)
              Searches the specified array of doubles for the specified value using the binary search algorithm.
    static int  binarySearch(float[] a, float key)
              Searches the specified array of floats for the specified value using the binary search algorithm.
    static int  binarySearch(int[] a, int key)
              Searches the specified array of ints for the specified value using the binary search algorithm.
    static int  binarySearch(long[] a, long key)
              Searches the specified array of longs for the specified value using the binary search algorithm.
    static int  binarySearch(Object[] a, Object key)
              Searches the specified array for the specified object using the binary search algorithm.
    static int  binarySearch(short[] a, short key)
              Searches the specified array of shorts for the specified value using the binary search algorithm.
    static
    <T> int
    binarySearch(T[] a, T key, Comparator<? super T> c)
              Searches the specified array for the specified object using the binary search algorithm.Sun公司的API里没有重载你这个方法啊你是不是自己重写了啊如果重写了,把Arrays的代码贴出来吧。
      

  4.   


    代码中有“Array.sort(arr); 

    排序了啊!
      

  5.   


    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
         int key) {
    int low = fromIndex; //0
    int high = toIndex - 1;  0 while (low <= high) {
        int mid = (low + high) >>> 1;  
        int midVal = a[mid];     if (midVal < key)
    low = mid + 1;   //1 
        else if (midVal > key)
    high = mid - 1;
        else
    return mid; // key found
    }
    return -(low + 1);  // key not found. // - 2
        }
    结果是-2 你可以对着源码看看。
      

  6.   

    还上粘上:如果没有找到那么返回: -( <i>insertion point </i>) - 1)