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 doesn't this code for a binary search function in c++ work?

#include <iostream>

int binary_search(int arr[], int size, int target)
{
    int first = 0;
    int last = size - 1; 
    int midpoint = (last + first) / 2;
    
    while(first <= last)
    {
        if(arr[midpoint] == target)
        {
            return midpoint;
        }
        else if(arr[midpoint] < target)
        {
            first = midpoint + 1;
        }
        else if(arr[midpoint] > target)
        {
            last = midpoint - 1;
            
        }
    }
    
    return 0;
}

int main()
{
    int arr[] = {4, 12, 23, 43, 50, 60, 230, 290};
    int size = sizeof(arr)/sizeof(arr[0]);
    int target = 12;
    std::cout << binary_search(arr, size, target);
}

if the midpoint value is lesser than the target it increases ‘first’ and if it’s greater than the target it instead decreases ‘last’. This continues until ‘first’ is equal to ‘last’.
I saw another program where they called the function recursively but i wanted to make it work without it, what exactly am i doing wrong?

>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

You basically forgot to update midpoint in each iteration.
An updated version of your code here (not using those "C" style arrays).It was also not clear if you meant to return the found value or the index at which it was found.

#include <iostream>
#include <vector>

std::size_t binary_search(const std::vector<int> values, int value)
{
    std::size_t first = 0;
    std::size_t last = values.size() - 1; // use vector it keeps track of its size
    
    while (first <= last)
    {
        std::size_t  midpoint  = (last + first) / 2; // you forgot to update midpoint each loop

        if (values[midpoint] == value)
        {
            return values[midpoint]; // <== do you want to return the position or the value?
        }
        
        if (values[midpoint] < value)
        {
            first = midpoint + 1;
        }
        else if (values[midpoint] > value)
        {
            last = midpoint - 1;
        }
    }

    return 0;
}

int main()
{
    std::vector<int> values{ 4, 12, 23, 43, 50, 60, 230, 290 };
    std::cout << binary_search(values, 12);
    return 0;
}
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