关于二分查找的一些想法

二分查找总结笔记。

1. 思想

:将一个有序的序列,不断的将中间的值和关键值做对比,如果相等就返回中间值;如果中间值大,那么就将中间值之前的序列 * 重新作为有序序列和关键字做对比,中间值小的情况也是一样。 * 最终找出关键值所在的位置。
**

2. 代码实现

1.使用非递归实现二分查找

public int binarySearch(int keyValue, int[] arr) {
        //分别给出首尾索引,和中间值索引
        int lowIndex=0;
        int higIndex = arr.length-1;

        while (lowIndex <= higIndex) {

            //由于可能涉及到多次对半的划分,所以动态的获取midIndex
            int midIndex = lowIndex + (higIndex - lowIndex) / 2;

            if (arr[midIndex] < keyValue) {
                lowIndex=midIndex+1;
            } else if (arr[midIndex] > keyValue) {
                higIndex = midIndex - 1;
            } else {
                return midIndex;
            }
        }
        return -1;
    }

2.使用递归方式实现二分查找

 public int RoundBinarySearch(int lowIndex, int higIndex, int[] arr,int value) {
        int midIndex = lowIndex + (higIndex - lowIndex) / 2;
        if (lowIndex <= higIndex) {
            if (arr[midIndex] == value) {
                return midIndex;
            } else if (arr[midIndex] < value) {
                lowIndex = midIndex + 1;
                return RoundBinarySearch(lowIndex, higIndex, arr, value);
            } else {
                higIndex = midIndex - 1;
                return RoundBinarySearch(lowIndex, higIndex, arr, value);
            }
        }
        return -1;
    }```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值