Arrays.binarySearch()的返回值


binarySearch()方法的返回值为:

  1、如果找到关键字,则返回值为关键字在数组中的位置索引,且索引从0开始

  2、如果没有找到关键字,返回值为负的插入点值,所谓插入点值就是第一个比关键字大的元素在数组中的位置索引,而且这个位置索引从1开始。

    注意:调用binarySearch()方法前要先调用sort方法对数组进行排序,否则得出的返回值不定,这时二分搜索算法决定的。

例如:

public static void main(String[] args) {
        int []sums = {2,3,1,4,3};
        int result = Arrays.binarySearch(sums,3);
        Arrays.sort(sums);
        int result2 = Arrays.binarySearch(sums,3);
        System.out.println(result+"---"+result2);
}

结果:-4---2

  

原文地址:https://www.cnblogs.com/firecode7/p/13216209.html