My understanding of (lower Bound,upper bound) binary search, in C + +, thanks to both post

Source: Internet
Author: User

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 of the range [first, last] that's greater than value.
Http://en.cppreference.com/w/cpp/algorithm/lower_bound
Returns an iterator pointing to the first element of the range [first, last] that's 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/

intBinarySearch ( vector<int>& Nums,intTarget) {//Return index of first one so 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    intfirst=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_boundFirst=mid+1;// first always increases        Else // Else recede lastLast=mid;//Last always decreases (even last-first==1)}returnFirst;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Ps. If in any-to-improment can be achieved, better performance or whatever, it'll be well-appreciated-let me know, thank s in advance.

My understanding of (lower Bound,upper bound) binary search, in C + +, thanks to both post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.