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 ?