#include<bits/stdc++.h>
using namespace std;
int binarySearch(int [], int, int, int);
int main()
{
int n, ar[50], givensum;
cout << "Enter the size of the array: ";
cin >> n;
for(int i = 0; i<n; i++)
{
cout << "ar[" << i << "] = ";
cin >> ar[i];
}
cout << "Enter the given sum: ";
cin >> givensum;
cout << "The closest sum possible is: " << binarySearch(ar, 0, n-1, givensum) << endl;
}
int binarySearch(int arr[], int l, int r, int key)
{
int mid = l+(r-l)/2;
while(l<=r)
{
if(arr[mid]==key)
return arr[mid]+1;
else if(arr[mid] > key)
r = mid-1;
else
l = mid+1;
}
return arr[mid];
}
The code is not printing the value returned by the function. Is the code wrong or the compiler is nuts? I tried storing the return value in another variable but it didn't work out. My interview for Blueflame Labs is scheduled for tomorrow. PLS HELP!!
Your binary search algorithm itself is wrong. It's stuck in an infinite loop.
Corrected code is as follows:
int binarySearch(int arr[], int l, int r, int key)
{
int mid = l+(r-l)/2;
while(l<=r)
{
if(arr[mid]==key)
return arr[mid];
else if(arr[mid] > key)
r = mid-1;
else
l = mid+1;
mid = l+(r-l)/2; //update the mid point so you're checking new points
}
return arr[mid];
}