算法--二分查找--求平方根(循环法/递归法)
发布日期:2021-07-01 03:39:36
浏览次数:2
分类:技术文章
本文共 1442 字,大约阅读时间需要 4 分钟。
二分查找:
- 数据需要是顺序表(数组)
- 数据必须有序
- 可以一次排序,多次查找;如果数据频繁插入,删除操作,就必须保证每次操作后有序,或者查找前继续排序,这样成本高,二分查找不合适
- 数据太小,不用二分查找,直接遍历
- 数据太大,也不用,因为数组需要连续的内存,存储数据比较吃力
- 复杂度 lg2n
题目: 求一个数的平方根
-
例如:二分法求根号5
a:折半: 5/2=2.5
b:平方校验: 2.5*2.5=6.25>5,并且得到当前上限2.5
c:再次向下折半:2.5/2=1.25
d:平方校验:1.25*1.25=1.5625<5,得到当前下限1.25
e:再次折半:2.5-(2.5-1.25)/2=1.875
f:平方校验:1.875*1.875=3.515625<5,得到当前下限1.875
循环求解:
#include递归求解:double rootbinarysearch(double num){ if(num == 1) return 1; double lower = 1, upper = num, curValue; if(lower > upper) std::swap(lower,upper); while(upper-lower > 0.00000001) { curValue = lower+(upper-lower)/2; if(curValue*curValue < num) lower = curValue; else upper = curValue; } return curValue;}int main(){ double x; std::cin >> x; std::cout << x << "的平方根是 " << rootbinarysearch(x); return 0;}
/** * @description: 求根号n,递归法 * @author: michael ming * @date: 2019/4/15 23:05 * @modified by: */#includedouble rootbinarysearch_R(double num, double upper, double lower){ if(num == 1) return 1; if(lower > upper) std::swap(lower,upper); double curValue = lower+(upper-lower)/2; if(upper-lower < 0.00000001) return curValue; if(curValue*curValue < num) return rootbinarysearch_R(num,curValue,upper); else return rootbinarysearch_R(num,lower,curValue);}int main(){ double x; std::cin >> x; std::cout << x << "的平方根是 " << rootbinarysearch_R(x,x,1); return 0;}
转载地址:https://michael.blog.csdn.net/article/details/89320746 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月23日 22时12分29秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
ubuntu sublime无法输入中文问题
2019-05-03
启用fcitx-qimpanel面板程序
2019-05-03
浅谈Q的基本实现
2019-05-03
python os模块
2019-05-03
iOS8 Push Notifications
2019-05-03
iOS8 PUSH解决方法
2019-05-03
Xcode6中如何添加pch文件
2019-05-03
iOS设备控制打印机输出文本
2019-05-03
IOS 网络请求中设置cookie
2019-05-03
Subversion基础:概念、安装、配置和基本操作(转)
2019-05-03
iOS开发之──传感器使用
2019-05-03
iOS开发之多媒体API(1)
2019-05-03
[深入浅出Cocoa]iOS网络编程之Socket
2019-05-03
[Cocoa]深入浅出Cocoa之Bonjour网络编程
2019-05-03
IOS之禁用UIWebView的默认交互行为
2019-05-03
iOS开发之多媒体播放
2019-05-03
iOS开发中的单元测试(三)——URLManager中的测试用例解析
2019-05-03
IOS 单元测试
2019-05-03
[深入浅出Cocoa]iOS程序性能优化
2019-05-03
http、TCP/IP协议与socket之间的区别
2019-05-03