二分查找

博客展示了二分查找的两种实现方式。一是一般方法,通过循环不断缩小查找范围;二是递归方法,在满足条件时不断调用自身进行查找。代码中给出了具体实现及测试示例,用于查找数组中指定整数的下标。

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

1.一般方法

public class Binary {
    /**
     * 二分查找
     * @param a 数组名字本身就是一个对象
     * @param x 要查找的整数值
     * @return  值在数组中的下标
     */
   public int binary_serach(int []a,int x)
    {
        int upper_bound=a.length-1,lower_bound=0,midpoint,value_at_midpoint;
        while(lower_bound<=upper_bound)
        {
            midpoint=(upper_bound+lower_bound)/2;
            value_at_midpoint=a[midpoint];
            if(value_at_midpoint==x)
                return midpoint;
            else if(value_at_midpoint<x)
                lower_bound=midpoint+1;
            else
                upper_bound=midpoint-1;
        }
        return 0;
    }
    public static void  main(String args[])
    {
        int []a= {1,2,3,4,5,6,7,8,9,10};
        Binary e=new Binary();
        System.out.println(e.binary_serach(a,7));
    }

}

2.递归

public class Binary_recursion {
    /**
     * 
     * @param a 数组名
     * @param x 查找的数值
     * @param upper_bound  上界
     * @param lower_bound  下界
     * @return 值在数组中的下标
     */
    public int binary_serach(int []a,int x,int upper_bound,int lower_bound)
    {
        int midpoint,value_at_midpoint;
        while(lower_bound<=upper_bound)
        {
                midpoint=(upper_bound+lower_bound)/2;
                value_at_midpoint=a[midpoint];
                if(value_at_midpoint==x)    
                return midpoint;
            else if(value_at_midpoint<x)
            {
                binary_serach(a,x,upper_bound,midpoint+1);
                
            }
            else {
                        binary_serach(a,x,midpoint-1,lower_bound);
            }
        }
        return 0;
    }

    public static void main(String[] args) {

        int []a= {1,2,3,4,5,6,7,8,9,10};
        Binary e=new Binary();
        System.out.println( e.binary_serach(a,7));
        
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值