二分查找实现

二分查找实现

1.调用Arrays中的binarySearch方法即可实现
【使用前提:数组必须为升序排列】

public class Demo1 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        //查找元素定为4
        int key = 4;
        int index1 = Arrays.binarySearch(arr, 4);
        //3
        System.out.println("对应的索引为:"+index1);
        int index2 = Arrays.binarySearch(arr, 11);
        //-11查找的元素不存在,返回的则是(-插入点-1)
        //插入点:如果这个元素在数组中,它应该在哪个索引上
        //-1是防止元素为0不存在,索引返回0,为了避免则-1
        System.out.println("对应的索引为:"+index2);
    }
}

打印结果:
-----------------------------------------------------
对应的索引为:3
对应的索引为:-11

2.其底层代码实现逻辑为:
【使用前提:数组必须为有序排列,下面为升序版,如果为降序则将start和end做替换】

public class Demo1 {
    public static void main(String[] args) {
         int []arr ={1,2,3,4,5,6,7,8,9,10};
         //查找元素定为4
        int key =4;
        //定义初始和结尾索引
        int index = getbinarySerach(arr, key);
        //对反回值做判断
        if(index!=-1){
            System.out.println(key+"对应的索引为"+index);
        }else {
            System.out.println("该数组中没有该元素");
        }
    }

    private static int getbinarySerach(int[] arr, int key) {
        int start =0;
        int end =arr.length-1,mid;
        //循环判断mid的值
        while (start<=end) {
             mid =(end+start)>>1;
            if(arr[mid]<key){
                start =mid +1;
            }else if(arr[mid]>key){
                end =mid -1;
            }else {
                return mid;
            }
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陪雨岁岁年年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值