Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this code not printing the value returned by the binarySearch() function?

#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!!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading