《算法四》二分查找

本文深入解析了二分查找算法的实现,包括普通和递归两种方式,详细介绍了如何在有序列表中查找指定元素,提供了完整的Java代码示例。

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

package com.algorithmic.find;

import java.util.List;

/**
 * @author: zhangxupeng
 * @date:2019/6/27
 * @Email: 1452806452@qq.com
 **/
public class BinarySearch {
    /**
     * 二分查找算法
     *
     * @param list list 必须是有序的
     * @param toFind 需要查找的数
     * @return -1 没找到
     */
    public static int find(List<Integer> list,int toFind){

//        return commonFind(list,toFind);
        return recFind(list,toFind,0,list.size()-1);
    }

    /**
     * 普通的二分查找
     * @param list list 必须是有序的
     * @param toFind 需要查找的数
     * @return -1 没找到
     */
    public static int commonFind(List<Integer> list, int toFind) {
        int size = list.size();
        int lowerBound = 0;
        int upperBound = size - 1;
        int curIn;
        while (true) {
            curIn = (lowerBound + upperBound) / 2;
            if (toFind == list.get(curIn)) {
                return curIn;
            } else if (lowerBound > upperBound) {
                return -1;
            } else {
                if (list.get(curIn) < toFind) {
                    lowerBound = curIn + 1;
                } else {
                    upperBound = curIn - 1;
                }
            }
        }
    }

    /**
     * 递归二分查找
     * @param list list 必须是有序的
     * @param toFind 需要查找的数
     * @param lowerBound
     * @param upperBound
     * @return -1没找到
     */
    public static int recFind(List<Integer> list,int toFind,int lowerBound,int upperBound){
        int curIn = (lowerBound+upperBound)/2;
        if (list.get(curIn)==toFind){
            return curIn;
        }else if (lowerBound>upperBound){
            return -1;
        }else {
            if (list.get(curIn)<toFind){
            //递归
                return recFind(list,toFind,curIn+1,upperBound);
            }else {
            //递归
                return recFind(list,toFind,lowerBound,curIn-1);
            }
        }

    }
}

代码下载地址:https://gitee.com/timezxp/algorithmic
参考书籍:https://www.javabbs.club/bbs/bbs/topic/86-1.html
至此,感谢!
欢迎添加关注!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

code 旭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值