C ++二进制搜索查找定点索引

时间:2013-08-24 09:09:39

标签: c++ algorithm binary-search-tree binary-search

我正在实现一个找到A [i] = i的固定点的函数。

size_t find_fixed_point(const vector<int>& list)
{
    auto lower = list.begin();
    auto upper = list.end() - 1;

    while (lower < upper)
    {
        auto mid = lower + (upper-lower)/2;

        if ( *mid <= (mid - list.begin()) )
        {
            // keep searching on left side
            upper = mid;
        }
        else
        {
            // keep searching on right side
            lower = mid + 1;
        }
    }

    return lower - list.begin();
}

所以如果我将它应用于以下向量

    vector<int> numbers = {-10, -5, 1, 3, 13, 13, 50, 70};

auto temp = find_fixed_point(numbers);
cout << numbers[temp];

它应该给3作为固定点,但它不起作用只是给我-10。

该算法看起来没问题,但不起作用。有人有想法吗?谢谢,

3 个答案:

答案 0 :(得分:2)

我认为你只是以错误的方式使用你的比较运算符:

size_t find_fixed_point(const vector<int>& list)
{
    auto lower = list.begin();
    auto upper = list.end() - 1;

    while (lower < upper)
    {
        auto mid = lower + (upper-lower)/2;

        if ( *mid >= (mid - list.begin()) )
        {
            // keep searching on left side
            upper = mid;
        }
        else
        {
            // keep searching on right side
            lower = mid + 1;
        }
    }

    return lower - list.begin();
}

答案 1 :(得分:0)

#include<iostream>
#include<vector>
using namespace std;

size_t find_fixed_point(const vector<int>& list)
{
    auto lower = list.begin();
    auto upper = list.end() - 1;

    while (lower < upper)
    {   
        auto mid = lower + (upper-lower)/2;

        if ( *mid > (mid - list.begin()) )
        {   
            // keep searching on left side
            upper = mid;
        }   
        else if ( *mid < (mid - list.begin()) )
        {   
            // keep searching on right side
            lower = mid + 1;
        }   
        else 
            return mid - list.begin();  
    }   
     return lower - list.begin();
}
int main()
{
    vector<int> numbers = {-10, -5, 1, 3, 13, 13, 50, 70};  
    auto temp = find_fixed_point(numbers);
    cout << numbers[temp];
}

答案 2 :(得分:0)

一个可行的解决方案是使用标准库算法,在这种情况下std::find_if()

int index = 0;
auto result = std::find_if( std::begin( v ) , std::end( v ) , [&]( int value ) { return value == index++; } );

但问题是std::find_if() O(n),使用简单的线性trasversal。

因此,如果您想要一个 O(logn)解决方案,就像在您的问题中一样,请使用二进制搜索解决方案。 我同意ilent2的答案,问题是“交换”比较:应该是>=,不是<=