二分法查找

一直感觉自己的基础太差 

我想自己还是老老实实的从基础开始

上家公司面试的时候有一道算法题 当场写一个二分查找,

现在依稀记得笔试的时候写的代码

在电脑上面敲出来 运行的时候 发现会报错 

经过调试之后 总算是可以得出结果了 下面我就把自己的码代码贴出来 


public class App {
    public static void main(String[] args) {
        int[] a = Util.createCommonNum();
        Util.syso(a);
        int key = Util.binarySearch(a , 0,12,9);
        System.out.println(key);
    }
}

public class Util {
    public static int binarySearch(int[] input , int start , int end ,int target ){
        int t , l , key;
        t = start;
        l = end;
        key = (end - start)/2 + start;
        while(key<end){
            if(target == input[key]){
                return input[key];
            }
            if(target - input[key] > 0){
                start = key;
                return  binarySearch(input ,start , end ,target );
            }else if(target - input[key] < 0){
                end = key;
                return binarySearch(input ,start , end ,target );
            }

        }
            return 0;
        }

    public static int[] createCommonNum(){
        int[] res = {1,2,3,4,5,6,7,8,9,10,11,12,13};
        return res;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值