鱼C论坛

 找回密码
 立即注册
查看: 3437|回复: 1

binary search 问题

[复制链接]
发表于 2018-3-25 22:38:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
In the binary search program on page 112, why did we write mid = beg + (end - beg) / 2; instead of mid = (beg + end) /2;?
  1. // text must be sorted
  2. // beg and end will denote the range we're searching
  3. auto beg = text.begin(), end = text.end();
  4. auto mid = text.begin() + (end - beg)/2; // original midpoint
  5. // while there are still elements to look at and we haven't yet found sought
  6. while (mid != end && *mid != sought) {
  7. if (sought < *mid) // is the element we want in the first half?
  8. end = mid; // if so, adjust the range to ignore the second
  9. half
  10. else // the element we want is in the second half
  11. beg = mid + 1; // start looking with the element just after mid
  12. mid = beg + (end - beg)/2; // new midpoint
  13. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-3-26 09:50:22 | 显示全部楼层
Isn't the same?

beg + (end - beg) / 2
= beg + end/2 - beg / 2
= beg / 2 + end/2
= (beg + end) /2
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-8 18:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表