0

This is the code for recursive binary search

Without using cout << binarySearch

int binarySearch(int arr[], int l, int h, int key)
{
    int mid = l + (h - l) / 2;
    if (l <= h)
    {
        if (arr[mid] == key)
        {
            return mid;
        }
        else if (key < arr[mid])
        {
            binarySearch(arr, l, mid - 1, key);
        }
        else
        {
            binarySearch(arr, mid + 1, h, key);
        }
    }
    else
        return -1;
}

int main()
{
    int arr[5] = {1,2,3,4,5};
    int key = 2;
    int size = sizeof(arr)/sizeof(arr[0]);
    cout << binarySearch(arr, 0, size - 1, key);
    return 0;
}

Output : 1

but when cout << binarySearch() is used the required output is changed

        else if (key < arr[mid])
        {
            cout << binarySearch(arr, l, mid - 1, key) << "\n"; // Adding cout here
        }
        else
        {
            cout << binarySearch(arr, mid + 1, h, key) <<"\n"; // Adding cout here
        }

Output : 1 1875946688 1875946688

Why the result is changed on using cout ?

Amish
  • 197
  • 1
  • 11
  • Obviously if you `cout` more things then you will get more things printed. Besides, your function doesn't always return a value. – interjay Jan 18 '22 at 13:33
  • As suggested by @interjay you should write `return binarySearch(arr, l, mid - 1, key);` – digito_evo Jan 18 '22 at 13:34

2 Answers2

2
return mid;

Here you have an explicit return statement that returns some value from this recursive function. So far, so good.

binarySearch(arr, l, mid - 1, key);

This is one of the recursive calls. When this recursive call returns ...nothing happens. The caller continues to execute. And after this statement ...nothing happens. The execution leaves from this function without explicitly returning anything. The caller to this function receives randomly-generated garbage as its return value.

Your compiler has an option to turn on all warnings. If it were used your C++ compiler would've likely pointed out this common bug.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

You have UB, since you don't return values on your recursive cases.

binarySearch(arr, l, mid - 1, key);

Should instead be

return binarySearch(arr, l, mid - 1, key);

For your cout version, you'd need something like

int ret = binarySearch(arr, l, mid - 1, key);
std::cout << ret;
return ret;
ChrisMM
  • 8,448
  • 13
  • 29
  • 48