Binary search and lower_bound, upper_bound

传统的二分查找是为了寻找目标数在一个有序数组中是否存在的问题。返回值为布尔型变量(true or false)。但是有时候需要知道更多信息,比如如果存在,那么在数组中该数出现的第一个位置(left most)和最后一个位置的索引是多少?如果不存在,那么如果把该数插入到数组中去,应该插入到哪个位置?

所以需要深入一步探索二分查找算法。C++中给出了几个库函数binary_search(),lower_bound() 和 upper_bound()。


binary_search()

Test if value exists in sorted sequence
Returns true if any element in the range [first,last) is equivalent to val, and false otherwise.
The elements are compared using operator < <script type="math/tex" id="MathJax-Element-1"><</script> for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a < <script type="math/tex" id="MathJax-Element-2"><</script>b) && !(b < <script type="math/tex" id="MathJax-Element-3"><</script>a)) or if (!comp(a,b) && !comp(b,a)).
The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val.
The function optimizes the number of comparison

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值