为什么 return 语句没有执行?二进制搜索

Why isn't the return statement executing? Binary Search

算法找到结果并测试为​​ true,但不 return de value 和 returns -2。有人知道为什么吗?我还没弄明白。 这是代码:

int recursiveBinarySearch(int* a, int p, int r, int x){

    if(p>r){
        return -1;
    }else{
        int m = (p+r)/2;
        cout<<(a[m]==x)<<endl;
        if(a[m]==x){
            cout<<"entering"<<endl;
            return (m+1);
            cout<<"wtf?"<<endl;
           }else if(x<a[m]){
               recursiveBinarySearch(a,p,m-1,x);
               }else if(x>a[m]) recursiveBinarySearch(a,m+1, r,x);

    }
    return -2;

}

这是输出($ := 我的输入):

>>$./a.out
>>Type the number of slots
>>0
>>Type a number to search for
>>
>>0
>>0
>>0
>>0
>>0
>>1
>>entering
>>The search did not return any item-2

当你递归调用recursiveBinarySearch( )时,你用return语句调用它,因为如果递归函数return是什么东西,调用递归函数的函数应该return相同的值。

代码应该是:

int recursiveBinarySearch(int* a, int p, int r, int x)
{
if(p>r)
    return -1;
else
{
    int m = (p+r)/2;
    cout<<(a[m]==x)<<endl;
    if(a[m]==x)
    {
        cout<<"entering"<<endl;
        return (m+1);
        cout<<"wtf?"<<endl;
    }
    else if(x<a[m])
      //Added a return statement to both the recurring function call.
    return recursiveBinarySearch(a,p,m-1,x);
    else if(x>a[m]) 
      //Added a return statement to both the recurring function call.
    return recursiveBinarySearch(a,m+1, r,x);
}
return -2;
}

recursiveBinarySearch 的 return 值在递归尝试写入时被忽略:

return recursiveBinarySearch(a,p,m-1,x);