JAVA二分查找源码阅读

本文详细介绍了JAVA中二分查找的实现方法,包括了范围检查、递归查找等关键步骤,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA二分查找
public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,T key, Comparator<? super T> c) {
        //首先进行范围检查   1
        rangeCheck(a.length, fromIndex, toIndex);
        //然后进行二分查找   2
        return binarySearch0(a, fromIndex, toIndex, key, c);
    }

1 rangeCheck

private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
        //如果起始下标大于结束下标抛出异常
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException(
                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); 
        }
        //如果起始下标小于0 抛出数组越界异常
        if (fromIndex < 0) { 
            throw new ArrayIndexOutOfBoundsException(fromIndex);
        }
        //如果结束下标大于数组长度 抛出数组越界异常
        if (toIndex > arrayLength) {
            throw new ArrayIndexOutOfBoundsException(toIndex);
        }
    }

2 binarySearch0

private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,T key, Comparator<? super T> c) {
        //查看比较器Compator是否是null
        if (c == null) {
            //执行默认比较器  3
            return binarySearch0(a, fromIndex, toIndex, key);
        }
       //省略
    }

3 binarySearch0(a, fromIndex, toIndex, key);

 private static int binarySearch0(Object[] a, int fromIndex, int toIndex,Object key) {
         //起始坐标给low
        int low = fromIndex;
        //终止坐标给high
        int high = toIndex - 1;
        //循环开始 如果 high >= low 那么执行
        while (low <= high) {
            //>>>右移运算符  (low+high)/2
            int mid = (low + high) >>> 1;
            @SuppressWarnings("rawtypes")
            //取出中间这个值
            Comparable midVal = (Comparable)a[mid];
            @SuppressWarnings("unchecked")
            //进行比较
            int cmp = midVal.compareTo(key);
            //如果cmp小于0 说明 key大于a[mid]
            if (cmp < 0)
                //那么low变为mid+1
                low = mid + 1;
            else if (cmp > 0)
                //key小于a[mid] 那么high变成mid-1
                high = mid - 1;
            else 
                //如果cmp==0那么key等于a[mid]返回mid下标
                return mid; // key found
        }
        //循环直到low > high时 结束
        //返回最相近的坐标的相反数
        return -(low + 1);  // key not found.
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值