二分查找(3.13)

来源:互联网 发布:大数据时代英文读后感 编辑:程序博客网 时间:2024/06/07 02:55

        在贴上程序前说几句。我在《programing pear》 看到有关这个算法的历史(was published in 1946,the first published binary search without bugs did not appear util 1962).整整16年时间,当时有那么多计算机的大牛怎么没有把今天看起来很一般的函数写对我自己到现在都没想明白。当然我不是说我的实现就没有bug当我想用一两时间写出一个没不bug的还是有可能的。

   十分赞成Jon Bentley 把编程分成几个阶段.(一)问题确定,试想连问题都没弄清楚,一上就写一堆代码再修修补补,只要用例一过就ok的程序是什么程序。(二)算法,Jon Bentley后面还提了许多优化程序的方法。现在有很多人都不想学算法而去追求那些新鲜的名词。要知道那些名词的后面都是算法(人工智能,神经网路,数据挖掘,这些不过是一堆优秀的算法)。(三)数据结构,效率是王道,有了一个好的ideal就要把把它表达出来,通用的数据结构正式这样一种语言(面向对象也是一种数据结构,她使程序员能更好更快的表达一部分问题,大的书设计模式也是的,结构是有机的不一堆积)。(四)程序的验证,不管是防御式编程,还是测试都是让我们向这条路走去。

   最后有爱因斯坦的一句话结尾,Everything should be made sa simple as possible,bu no simpler.

 

public class BinSearch {

    public static int binSearch(int[] nums, int x) {
        int re = -1;
        if (nums == null)
            return re;
        else {
            int start = 0;
            int end = nums.length - 1;
            while (end >= start) {
                int mid = (start + end) / 2;
                if (x > nums[mid])
                    start = mid + 1;
                else if (x < nums[mid])
                    end = mid - 1;
                else
                    return mid;
            }

        }
        return re;
    }

    public static void main(String[] args) {
        int[] test = { 1, 2, 3, 5, 6, 7, 9 };
        System.out.println(binSearch(test, 40));
    }
}

原创粉丝点击