Binary Search

#include<bits/stdc++.h>
#define ll long long

// Return the INDEX of the LEFTMOST element that is >= a value. 
// Return -1 if not found.
template <typename T>
int bsearch_leftmost_larger_or_equal(T *array, 
        int first_idx, int last_idx, T value, bool shouldSort) {
    
    if (shouldSort) {
        sort(array + first_idx, array + last_idx);
    }
    
    int first = first_idx, last = last_idx, mid;
    
    while (first != last) {
        mid = (first + last) / 2;
        
        if (array[mid] >= value)
            last = mid;
        else
            first = mid + 1;
    }
    
    if (array[first] >= value)
        return first;
    else
        return -1;
    
}

Leave a Reply