c++ - 在排序数组中查找旋转点

标签 c++ arrays binary-search

我试图通过修改后的二进制搜索在排序数组中定位旋转点。

考虑这个数组 int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; 这里的旋转点在 index = 3 处,即在 9 处。

我为上面的操作写了这个函数。

void FindRotationPoint(int values[], int numvalues)
{
    int first =0;
    int last = numvalues-1;
    int middle;
    bool moreTosearch= (first<=last);
    while(first<=last)
    {
        middle = (first+last)/2;
        if(values[0]>values[middle]) //Keep looking right if the middle value in array is greater than first
        {
            last = middle-1;
        }
        if (values[0]<values[middle]) //Keep looking left if the middle value in array is less than first
        {
            first = middle+1;
        }
    }
    cout<<middle+1<<endl;
    cout<<values[middle];
}

如果元素是 int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; 输出:4, 1(错误)

int values[9]={7, 8, 9, 10, 2, 3, 4, 5, 6}; 输出:4, 10(正确)

找到偶数位置的旋转点是正确的,而在其他情况下,它找到了后续元素。我在上面的代码中缺少什么?

最佳答案

这个有效:

void FindRotationPoint(int values[], int numvalues)
{
    int first =0;
    int last = numvalues-1;
    int middle=0;
    bool moreTosearch= (first<=last);
    while(first<last)
    {
        middle = (first+last)/2;
        if(values[first]>=values[middle]) //Keep looking right if the middle value in array is greater than first
        {
            last = middle;
            cout<<"first>middle: "<<first<<" "<<middle<<" "<<last<<"\n";
        }
        else if (values[middle]>=values[last]) //Keep looking left if the middle value in array is less than first
        {
            first = middle;
            cout<<"middle<last: "<<first<<" "<<middle<<" "<<last<<"\n";
        }
    }
    cout<<middle+1<<endl;
    cout<<values[middle];
}

int main()
{
int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6};

FindRotationPoint(values, 9);
return 0;
}

关于c++ - 在排序数组中查找旋转点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7369654/

相关文章:

c++ - 从 C++ 如何执行 C 中的方法或访问结构?

c++ - QTableView 上的 SQL 参数计数不匹配

c - 从已编译的搜索程序中提取记录,C

c - 在 C 中为数组的元素分配随机值

使用 char 数组的 C++ 二进制搜索

Python 线性搜索效率更高

c++ - 是否可以在 Visual Studio 2012 中配置性能 session 文件 (VSP) 的位置?

c++ - 使用 Rcpp 使用最新的 QuantLib 代码

javascript - 使用 splice() 就地更改数组

javascript - 如何遍历对象数组并计算存在多少个重复值?