Implementation of C lower_bound

后端 未结 8 1448
北恋
北恋 2020-12-12 18:48

Based on the following definition found here

Returns an iterator pointing to the first element in the sorted range [first,last) which does not com

8条回答
  •  情深已故
    2020-12-12 18:50

    C++ Implementation

    int binary_search_lower_bound(vector& array, int target) {
        int lo = 0, hi = (int)array.size();
        int mid;
    
        while(lo < hi) {
            mid = lo + ((hi - lo) >> 1);
            int val = array[mid];
            if (target <= val)//array[mid])
                hi = mid;
            else
                lo = mid + 1;
        }
    
        return lo;
    }
    

    Edit: Fixed bug for non-existing value.

提交回复
热议问题