#if !defined HAVE_BSEARCH_H__
#define      HAVE_BSEARCH_H__


#include "fxttypes.h"


template <typename Type>
ulong bsearch(const Type *f, ulong n, const Type v)
// Return index of first element in f[] that equals v
// Return ~0 if there is no such element.
// f[] must be sorted in ascending order.
// Must have  n!=0
{
    ulong nlo=0, nhi=n-1;
    while ( nlo != nhi )
    {
        ulong t = (nhi+nlo)/2;

        if ( f[t] < v )  nlo = t + 1;
        else             nhi = t;
    }

    if ( f[nhi]==v )  return nhi;
    else              return ~0UL;
}
// -------------------------


template <typename Type>
ulong bsearch_ge(const Type *f, ulong n, const Type v)
// Return index of first element in f[] that is >= v
// Return ~0 if there is no such element.
// f[] must be sorted in ascending order.
// Must have  n!=0
{
    ulong nlo=0, nhi=n-1;
    while ( nlo != nhi )
    {
        ulong t = (nhi+nlo)/2;

        if ( f[t] < v )  nlo = t + 1;
        else             nhi = t;
    }

    if ( f[nhi]>=v )  return nhi;
    else              return ~0UL;
}
// -------------------------


template <typename Type>
ulong bsearch_le(const Type *f, ulong n, const Type v)
// Return index of first element in f[] that is <= v
// Return ~0 if there is no such element.
// f[] must be sorted in ascending order.
// Must have  n!=0
{
    ulong nlo=0, nhi=n-1;
    while ( nlo != nhi )
    {
        ulong t = (nhi+nlo)/2;

        if ( f[t] > v )  nlo = t + 1;
        else             nhi = t;
    }

    if ( f[nhi]<=v )  return nhi;
    else              return ~0UL;
}
// -------------------------


#endif // !defined HAVE_BSEARCH_H__
