0

I've been looking over and over this for a while but I can't seem to understand what's wrong with it.

I run the ./find and the terminal and this is what I see: Terminal

My code is as follows:

bool search(int value, int values[], int n)
{
    if (value < 0)
    {
        return false;
    }
    else
    {
        int max = n - 1;
        int min = 0;
        int middle;

        while (max >= min)
        {
            middle = (min + max) / 2;
            if (values[middle] == value)
            {
                return true;
            }
            else if (values[middle] > value)
            {
                max = values[middle - 1];
            }
            else if (values[middle] < value)
            {
                min = values[middle + 1];
            }
        }
    return false;
}   

I'd appreciate any kind of help since I feel very stuck at the moment.

Thank you!

1

I think the issue is with how you are using your max and min variables. It looks like from how you initialize them, you are using them as the indices of the first and last elements of the section of the haystack array (values[]) that you are searching.

When you reassign them in your else if blocks, you are giving them actual values from the haystack at certain indices:

max = values[middle - 1];

In the line above for example, you are taking the value of the element just to the left of the middle element and putting it in max. It seems more likely you want to simply assign the index just left of middle to max, like so:

max = middle - 1;

Similar logic should apply for min.

Hope this helps.

1
  • You are absolutely right!!! Thanks so much!
    – GerardR
    Oct 21 '15 at 5:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .