地球人都知道“二分查找”,方法也非常简单,但是你能不能在10分钟内写出一个没有bug的程序呢?

知易行难,自己动手写一下试一试吧。

public class BinarySearch {
    public static int search(int [] A,int target,int a, int b)
    {
        int  middle = (a+b)/2;
        if(a>b)
            return -1;
        else if (A[middle]==target)
            return middle;
        else if (A[middle]< target)
            return search(A,target,middle+1,b);
        else
            return search(A,target,a,middle-1);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int A [] = {2,4,6,8,10};
        System.out.println( BinarySearch.search(A,1 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,2 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,3 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,4 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,5 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,6 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,7 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,8 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,9 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,10 , 0, A.length-1) );
        System.out.println( BinarySearch.search(A,11 , 0, A.length-1) );
    }
}

上面的代码看似是没有任何问题了,但是呢,其实还是有一个很微妙的bug,这个bug发生在:

int  middle = (a+b)/2;

这一行。想一下,如果a+b超出了Int型的最大值了呢???所以呢,修正这个bug应该这样:
public class BinarySearch {
    public static int search(int [] A,int target,int a, int b)
    {
        int  middle = a+(b-a)/2;
        if(a>b)
            return -1;
        else if (A[middle]==target)
            return middle;
        else if (A[middle]< target)
            return search(A,target,middle+1,b);
        else
            return search(A,target,a,middle-1);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int A [] = {2,4,6,8,10};
        System.out.println( BinarySearch.search(A,1 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,2 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,3 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,4 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,5 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,6 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,7 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,8 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,9 , 0, A.length-1)  );
        System.out.println( BinarySearch.search(A,10 , 0, A.length-1) );
        System.out.println( BinarySearch.search(A,11 , 0, A.length-1) );
    }
}

查找一个元素是否存在,自然分为“存在”和“不存在”两种情况。在思考二分查找的时候,先思考“存在”的情况,设计算法,然后再去考虑“不存在”的情况。

如果同时思考“存在”和“不存在”两种情况,那么很容易被绕晕。

《算法导论》习题2.3-5 二分搜索 Binary Search的更多相关文章

  1. 【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】

    [096-Unique Binary Search Trees(唯一二叉搜索树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given n, how many s ...

  2. 数据结构与算法--二分搜索(binary search)

    前言 之前面试准备秋招,重新翻起了<编程之美>.在第三章节看到了一道关于二分搜索的讨论,觉得有许多细节是自己之前也没怎么特别注意地方,比如二分搜索的初始条件,转化.终止条件之类的. 问题 ...

  3. LeetCode算法题-Lowest Common Ancestor of a Binary Search Tree

    这是悦乐书的第197次更新,第203篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第59题(顺位题号是235).给定二叉搜索树(BST),找到BST中两个给定节点的最低共 ...

  4. 二分搜索 - Binary Search

    二分搜索是一种在有序数组中寻找目标值的经典方法,也就是说使用前提是『有序数组』.非常简单的题中『有序』特征非常明显,但更多时候可能需要我们自己去构造『有序数组』.下面我们从最基本的二分搜索开始逐步深入 ...

  5. 算法学习记录-查找——折半查找(Binary Search)

    以前有个游戏,一方写一个数字,另一方猜这个数字.比如0-100内一个数字,看谁猜中用的次数少. 这个里面用折半思想猜会大大减少次数. 步骤:(加入数字为9) 1.因为数字的范围是0-100,所以第一次 ...

  6. 《算法导论》习题2.3-6 改进的InsertSort

    InsertSort中有关键的一步是把当前元素A[i]插入到已经排好序的A[1,i-1]的合适的位置上,在原始的InsertSort算法中, 采用的是从后往前一步一步查找的方法,习题2.3-6要求利用 ...

  7. [置顶] 《算法导论》习题解答搬运&&学习笔记 索引目录

    开始学习<算法导论>了,虽然是本大部头,可能很难一下子看完,我还是会慢慢地研究的. 课后的习题和思考有些是很有挑战性的题目,我等蒻菜很难独立解决. 然后发现了Google上有挺全的algo ...

  8. (搬运)《算法导论》习题解答 Chapter 22.1-1(入度和出度)

    (搬运)<算法导论>习题解答 Chapter 22.1-1(入度和出度) 思路:遍历邻接列表即可; 伪代码: for u 属于 Vertex for v属于 Adj[u] outdegre ...

  9. 算法导论课后习题解答 第一部分 练习1.1-1->1.1-5

    很高兴能和大家一起共同学习算法导论这本书.笔者将在业余时间把算法导论后面的题解以博文的形式展现出来希望能得到大家的支持谢谢.如果有可能我会做一些教学视频免费的供大家观看. 练习题选自算法导论中文第三版 ...

随机推荐

  1. 字段为空sql语句,设置当前模式

    delete from t_corpinfo  where CORPID='' and CORPNAME=''  该命令是删除字段为空的记录 SET CURRENT SCHEMA DB2INST1;

  2. linux系统定时重启tomcat

    #touch auto-start.sh [root@Linux opt]# echo $LANGen_US.UTF-8 #vim auto-start.sh #!/bin/sh export LAN ...

  3. 《割绳子》《蜡笔物理学》《Contre Jour》《顽皮鳄鱼爱洗澡》等游戏用Box2D引擎实现物理部分的方法(转)

    从最热门游戏排行榜和flash游戏网站上,你能看到什么?许多2D游戏都有非常出色的物理学和美术设计.现在我们要学习那些游戏使用了什么物理学以及如何用Box2D制作它们. 除了知道是“什么”,更重要的是 ...

  4. A SPI class of type org.apache.lucene.codecs.PostingsFormat with name 'Lucene40' does not exist.

    简单的建立索引和查询索引并不难,关键在于他的二次开发,让他适合你自己的需求 既然要二次开发就必须查看源码 首先看看索引过程中的核心类吧: IndexWriter 这个是核心组件, 建立和打开索引,以及 ...

  5. eclipse,android Localization (Internationalization) 安卓本地化(国际化)

    1.创建新的资源文件,名字保持一致.提示"已存在",继续. 2.使用“语言”作为识别器,然后选择相应的语言代码.Tips:其他的适配,如国家.屏幕大小等,也是通过这里的识别器实现适 ...

  6. 未能读取并闩锁页 (1:xxxxx)(用闩锁类型 SH)

    设置数据库为紧急模式 停掉SQL Server服务: 把应用数据库的数据文件XXX_Data.mdf移走: 重新建立一个同名的数据库XXX: 停掉SQL服务: 把原来的数据文件再覆盖回来: 运行以下语 ...

  7. Android的Activity跳转动画各种效果整理

    Android的Activity跳转就是很生硬的切换界面.其实Android的Activity跳转可以设置各种动画,本文整理了一些,还有很多动画效果,就要靠我们发挥自己的想象力 大家使用Android ...

  8. 转: window中使用PSFTP/WinSCP实现SFTP上传下载

    sftp 服务器:  dbmonitor 1.sftp属于交互式的,所以你得缓存下命令#!/bin/shsftp -o Port=3322 root@172.16.1.21:/opt << ...

  9. 【矩阵压缩】 poj 1050

    题意:给一个矩阵,里面有正负数,求子矩阵和的最大值 #include <iostream> #include <cstdio> #include <stdlib.h> ...

  10. App installation failed There was an internal API error.

    工程名为汉字的时候,真机调试会出现这种问题.模拟器没有问题. 如图: 解决办法: