c++ - 递归二进制搜索实现正在崩溃......为什么?

标签 c++ pointers recursion binary-search

我正在尝试查找并修复此代码中的问题。它是通过递归实现的二进制搜索。我不知道它为什么会返回堆栈溢出和崩溃。

bool find( const int x, const int* pBegin, const int* pEnd)
{
    int medel = (*pBegin +(( *pEnd-1) - *pBegin)/2) ;

    if(x == medel)
        return true ;

    else if( x > medel) 
    {
        int begin = (medel +1);

        return find (x, &begin, pEnd);
    }
    else if( x< medel)
    {
        int last = (medel-1);

        return find(x,pBegin, &last);
    }

}


void main()
{
    int arr[10];
    for (int i=0;i<10;++i)
        arr[i] = i;
    bool hittat = find(7, &arr[0], &arr[9]);
    cout << "hittat = " << hittat << endl;

    system("pause");
}

当我调试代码时,我看到调用函数“find”时它采用了奇怪的参数,例如 this pic .

它应该使用 0 和 9,而不是这些巨大的数字:/ 我的指点有什么问题吗?

最佳答案

您应该计算指针 的平均值,并检查它们之间的元素走廊的 是多少。相反,您计算它们所指向的的平均值,这明显不同。

关于c++ - 递归二进制搜索实现正在崩溃......为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540652/

相关文章:

c++ - 链接到共享的 boost 库让人头疼

c++ - 1 个多线程文件描述符,显示 losf 上的多个打开文件

c++ - 从同一项目中的两个 C++ 文件调用同一头文件中的函数

c - 特定地址的内存转储的最佳数据类型

没有isinstance的列表列表上的python递归(不同)

c++ - 我应该如何递归调用模板函数?

c - 访问其指针从函数返回的结构中的二维数组时出现段错误

c - strcpy 示例程序中的缺陷

java - 这段代码中的中序遍历有什么问题?

scala - 何时对递归函数/方法使用辅助递归函数/方法