Oct 2, 2025

[Algorithm] branchless binary search

template <class ForwardIt, class T, class Compare>
ForwardIt branchless_lower_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    auto length = last - first;

    while (length > 0)
    {
        auto half = length / 2;
        // multiplication (by 1) is needed for GCC to generate CMOV
        // comp returns 1 if value > first[half], returns 0 otherwise
        first += comp(first[half], value) * (length - half); 
        length = half;
    }

    return first;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.