def _searchsorted(array, val, side='left'):
    """
    Call np.searchsorted or use a custom binary
    search if necessary.
    """
    if hasattr(array, 'searchsorted'):
        return array.searchsorted(val, side=side)
    begin = 0
    end = len(array)
    while begin < end:
        mid = (begin + end) // 2
        if val > array[mid]:
            begin = mid + 1
        elif val < array[mid]:
            end = mid
        elif side == 'right':
            begin = mid + 1
        else:
            end = mid
    return begin
