my understanding of (lower bound,upper bound) binary search, in C++, thanks to two post

If you understand the comments below, never will you make mistakes with binary search!
thanks to A simple CPP solution with lower_bound
and C++ O(logn) Binary Search that handles duplicate, thanks to phu1ku ‘s answer on the second post.
http://en.cppreference.com/w/cpp/algorithm/upper_bound
Returns an iterator pointing to the first element in the range [first, last) that is greater than value.
http://en.cppreference.com/w/cpp/algorithm/lower_bound
Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value.

If want to practice, code on your own, try https://leetcode.com/problems/search-insert-position/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ , https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ and https://leetcode.com/problems/search-a-2d-matrix-ii/ , and see the discusses.

int binarySearch(vector<int>& nums, int target) {
    /// return index of first one that comp(item,target)==true, or nums.size() if not found
    /// comp is greater or equal to for lower_bound
    /// comp is greater for upper_bound
    int first=0, last=nums.size(), mid;
    while (first<last) {
        mid=first+((last-first)>>1); // first<=mid, mid<last
        /// if comp(item,target)==false, advance first
        // if(nums[mid]<=target) // for upper_bound
        if (nums[mid]<target) // for lower_bound
        first=mid+1; // first always increases
        else /// else recede last
        last=mid; // last always decreases (even last-first==1)
    }
    return first;
}
def bsearch(seq, key):
    """
    return index of first item in seq such that key(item) is true, 
    if no such item exist, return len(seq)
    """
    l, r = 0, len(seq)
    while l<r:
        mid = l+(r-l)/2
        if key(seq[mid]):
            r = mid
        else:
            l = mid + 1
    return r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值