Arrays.binarySearch详解

本文详细探讨了Java中的Arrays.binarySearch API,包括其在有序递增数组中的工作原理、不同情况下的返回值分析,以及如何处理数组为空的情况。通过源代码解析,解释了返回值与插入点的关系,并给出了实例验证,帮助读者深入理解该API的使用。
摘要由CSDN通过智能技术生成

Arrays.binarySearch是系统库提供的二分查找api。

先看看源代码中的注释

 /**
     * Searches the specified array of ints for the specified value using the
     * binary search algorithm.  The array must be sorted (as
     * by the {@link #sort(int[])} method) prior to making this call.  If it
     * is not sorted, the results are undefined.  If the array contains
     * multiple elements with the specified value, there is no guarantee which
     * one will be found.
 **/

这说明:该api只能用于有序递增数组(所以一般配合Arrays.sort使用),且数组中若有重复值,无法保证获得哪个值

重载“狂魔”

首先提及一下,该api提供了多个重载方法。支持八大基本类型除了boolean外(毕竟boolean数组也跟查找没多大关系),还支持Object类型和泛型,可以说是应有尽有。

此处以int类型为例说明,其它实现也大同小异

    public static int binarySearch(int[] a, int key) {
   
        return binarySearch0(a, 0, a.length, key);
    }
public static int binarySearch(int[] a, int fromIndex, int toIndex,int key) {
   
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值