Search code examples
c++pointersreturnbinary-search

C++ Function return value: my function is set to return a pointer but is not returning anything


So, I'm doing an algorithm with the intention of running a binary search. But the problem is even with the algorithm working inside the function my return does not work at all, the return I always receive is 0. Here is the function that is doing the search:

value_type* bsearch( value_type * first, value_type * last, value_type value ){
   value_type* mid;
   mid = (last - first)/2 + first;
   if(first>last){
     std::cout << "first>last" << value << *mid << '\n';
     return nullptr;
   }
   if(*mid==value){
     std::cout << "Found " << mid << " " << *mid << '\n';
     return mid;
   }
   if(*mid>value){
     last = mid - 1;
     std::cout << "*mid>value " << mid << " " << *mid << '\n';
     bsearch(first,last,value);
   }else{
     first = mid + 1;
     std::cout << "*mid<value " << mid << " " << *mid << '\n';
     bsearch(first,last,value);
  }
  return nullptr;
}

And here is the function that is running the bsearch function. The result is always equals to 0 even when mid is a valid pointer, so the output is always "Search failed!".

void run_bsearch(){
    value_type A4[]{ 1, 2, 3, 4, 5, 6, 7 };

    std::cout << ">>> A4[ " << print( std::begin(A4), std::end(A4) ) << "]\n";
    for ( auto i(0u) ; i <= (sizeof(A4)/sizeof(A4[0]))+1 ; ++i ){
        std::cout << ">>> Looking for value \'" << i << "\' in A4: ";
        value_type* result = bsearch( std::begin(A4), std::end(A4), i );
        std::cout << "Result: "<<result << "\n";
        if( result == nullptr ){
          std::cout << "Search failed!\n";
        }else{
          std::cout << "Located target element at position " << result - std::begin(A4) << std::endl;
        }
    }
}

The program runs like this:

Here is a print of the program running


Solution

  •   if(*mid>value){
         last = mid - 1;
         std::cout << "*mid>value " << mid << " " << *mid << '\n';
         bsearch(first,last,value);
       }else{
         first = mid + 1;
         std::cout << "*mid<value " << mid << " " << *mid << '\n';
         bsearch(first,last,value);
      }
    

    The problem here is that you're not returning the result of the recursive bsearch function.