码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-08-01 15:46:53      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:search   cpp   

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, https://leetcode.com/problems/search-insert-position/

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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。// ps. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

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

标签:search   cpp   

原文地址:http://blog.csdn.net/qeatzy/article/details/47186223

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!