c ++通过递归进行二进制搜索

时间:2015-10-20 18:50:20

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

第一次递归调用时收到错误,错误:

  

rekBinSearch.exe中0x002A2E44处的未处理异常:   0xC0000005:访问冲突读取位置0x0000000A。

原因是:

  

if((* pEnd - pBegin)== 0)/ 只有一个元素* /

似乎当我设置新的开始和结束地址时,我做错了,因为这些在递归调用中无法读取。他们被“设定”:

  

find(x,(int *)pBegin,pMid);

完整代码:

    bool find(const int x, const int* pBegin, const int* pEnd)
{
   if ((*pEnd - *pBegin) == 0) /* There's only one element */
    {
        if (x == (int)pEnd)    /* That element could be the correct one */
            return true;
        else                   /* If it is not then return false, x is not in the array */
            return false;
    }

    int *pMid = (int*)(pEnd - pBegin);  /* pMid should be the adress to the element in the middle of the array */
    if (x >= (int)pMid)                 /* If x is in array it is to the right of the middle */
        find(x, (int*)pMid, pEnd);  
    else                                /* If x is in array it is to the left of the middle */           
        find(x, (int*)pBegin, pMid);

}// find

我做错了什么或我怎么想错了?谢谢我的进步。

2 个答案:

答案 0 :(得分:2)

  

我做错了什么或我怎么想错了?谢谢我的进步。

问题1

你在指针和值之间混淆。例子:

if (x == (int)pEnd)

int(pEnd)

pEnd未获取int指向的对象的值。它只是将指针值视为 find(x, (int*)pMid, pEnd); // Missing return

问题2

此外,您没有从递归调用中正确返回。

    find(x, (int*)pBegin, pMid); // Missing return

bool find(const int x, const int* pBegin, const int* pEnd)
{
   if ((pEnd - pBegin) == 0) /* There's only one element */
   {
      return (x == *pEnd);  /* That element could be the correct one */
                            /* If it is not then return false, x is not in the array */
   }

   int midIndex = (pEnd - pBegin)/2;
   int const* pMid = pBegin + midIndex; /* pMid should be the adress to the element in the middle of the array */
   if (x >= *pMid)                     /* If x is in array it is to the right of the middle */
      return find(x, pMid, pEnd);  
   else                                /* If x is in array it is to the left of the middle */           
      return find(x, pBegin, pMid-1);

}// find

修正了功能

这是一个应该有效的版本。

{{1}}

答案 1 :(得分:0)

你想要if ((pEnd - pBegin) == 0)吗?请注意,没有解除引用指针。取消引用pend总是一个坏主意,因为它没有指向任何东西。

相关问题