博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
编程之美:无差错二分查找
阅读量:7286 次
发布时间:2019-06-30

本文共 1128 字,大约阅读时间需要 3 分钟。

1.虽然二分查找是十分简单的程序,但是因为循环等操作也是最容易出错的,其中在写循环(或者递归)程序的时候,应该特别注意三个方面的问题:初始条件、转化、终止条件。

 

2.二分查找源码

int biseach(char** arr, int b, int e, char* v){    int minIndex = b, maxIndex = e, midIndex;        while(minIndex < maxIndex - 1)                           //若改为minIndex < maxIndex时,容易出现死循环     {                                                        //eg:minIndex=2 maxIndex=3时就进入死循环           midIndex = minIndex + (maxIndex - minIndex) / 2;   //若midIndex =(minIndex + maxIndex)/2,在上溢的时候,会导致midIndex.           if(strcmp(arr[midIndex], v) <= 0)          {              minIndex = midIndex;          }          else          {              maxIndex = midIndex;                           }    }                                                       //退出循环时:若minIndex为偶数则minIndex==maxIndex,                                                             //否则就是minIndex == maxIndex  - 1         if(!strcmp(arr[maxIndex], v))    {          return maxIndex;    }    else if(!strcmp(arr[minIndex], v))    {         return minIndex;    }    else    {        return -1;    }}

 

转载于:https://www.cnblogs.com/biyeymyhjob/archive/2012/08/18/2645124.html

你可能感兴趣的文章
oracle避免约束带来的导入数据解决方案
查看>>
多行文本字段运行时展示成单行文本
查看>>
sharepoint 禁用使用资源管理器打开
查看>>
jquery iframe弹出多选框
查看>>
记某个客户不能通过HTTPS访问在AWS部署站点的问题
查看>>
[Voice Tips 2] IPHONE
查看>>
Ubuntu Server版安装Gnome图形桌面
查看>>
360抢夺“度娘”?
查看>>
我的友情链接
查看>>
firewall-cmd防火墙概述
查看>>
Redhat+Nginx0.8.46+PHP5.2.14+Mysql5.1.46构建LNMP(X64)平台
查看>>
win8 体验
查看>>
LAMP环境搭建图形界面配置MySQL数据库
查看>>
Microsoft + GitHub = 给开发者赋能
查看>>
django实例教程
查看>>
swift 中String常用操作
查看>>
oracle lock基础知识(一)
查看>>
eclipse alt+/ 无法使用或者显示不了方法
查看>>
[微擎]更改微擎后台顶部导航配色
查看>>
web报表functionChart教程
查看>>