简体   繁体   中英

Binary Search Recursion warning

#include <iostream>
using namespace std;
int i = 0;
int binarySearch(int arr[],int left, int right, int item)
{
    int midpoint;
    bool found{false};
    if(left < right && !found)
    {
        midpoint = left + (right - left)/2;
        if(arr[midpoint]<item)
        {
            binarySearch(arr,midpoint+1,right,item);
        }
        else if(arr[midpoint]>item)
        {
            binarySearch(arr,left,midpoint-1,item);
        }
        else
        {
            found = true;
            return midpoint;
        }
    }

}
int main()
{
    int arr[] = {10,20,30,40};
    int x = binarySearch(arr,0,3,40);
    cout << x ;
}

How is it returning the correct value of the item searched for although its not even reaching the return statement. It is reaching the base case when it is only one element in the array, but it should not reach the return statement, thus it should return garbage, but it is returning the correct index every time.

In most cases you don't return any value so you get whatever happens to be in the result register or stack slot at the time. This can work by accident, if you are unlucky.

Turn on compiler warnings and always fix them. Best to turn warnings into errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM