二分法查找

来源:互联网 发布:feeling软件 编辑:程序博客网 时间:2024/06/06 11:42

一直感觉自己的基础太差 

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

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

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

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

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


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;    }}



原创粉丝点击