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