0

When I try running find.c inputting:

./generate 1000 50 | ./find 127

it should return that the value (127) was found, however when I do it with my code, it seems to create an infinite loop.

Also, when I run the check50 on it, it returns:

:) helpers.c exists
:) helpers.c compiles
:) finds 42 in {42,43,44}
:) finds 42 in {41,42,43}
:( finds 42 in {40,41,42}
   \ killed by server
:) finds 42 in {41,42,43,44}
:( finds 42 in {40,41,42,43}
   \ killed by server
:( finds 42 in {39,40,41,42}
   \ killed by server
:( doesn't find 42 in {39,40,41}
   \ killed by server
:( doesn't find 42 in {39,40,41,43}
   \ killed by server
:( finds 42 in {42,40,39,41}
   \ killed by server

After looking into it, I believe the problem may be with my binary search function but I don't know exactly what is wrong. The code is:

bool binarySearch(int value, int values[], int n)
{

    int start = 0;
    int end = n - 1;
    int middle = (start + end) / 2;

    while (end >= start)
        {

        if (values[middle] == value)
        {
            return true;
        }

        else if (values[middle] > value)
        {
            end = middle - 1;
        }

        else
        {
            end = middle + 1;
        }

        middle = (start + end) / 2;

    }

    return false;

}

While looking for solutions, I read that the problem may have been from when the value I'm looking for is at the start or end of the array, but after adding in a simple check to see if the value I'm looking for is in index 0 or index n - 1, I still didn't get everything right and it'd still loop. I also added a hard 'stop' (just a simple counter that breaks out of the loop when it hits n loops) to the function along with the above check and while it wouldn't create an infinite loop, it wouldn't be able to return whether the value was found or not correctly all the time. Any help at this point would be appreciated.

1

Seems you just misprinted. Change

end = middle + 1

to

start = middle + 1

and it will work just fine.

You must log in to answer this question.

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