# pset3 search: expected an exit code of 0 not 1

I keep returning an exit code of 1 instead of 0 even if I manage to find the value inside the array. I suspect something is wrong with my while loop but I can't exactly pinpoint it. Any help is greatly appreciated. Thanks!

``````bool search(int value, int values[], int n)
{
//implement a binary search algorithm
int high = n - 1;
int low = 0;
int midpoint = (high + low)/2;
int comparer(int midpoint, int value, int values[]);

while(low <= high)
{
int result = comparer(midpoint, value, &midpoint);

if (result == 0)
{
return true;
}

else if(result == 1)
{
high = midpoint - 1;
midpoint = (high + low)/2;
}

else if(result == -1)
{
low = midpoint + 1;
midpoint = (high + low)/2;
}

}
return false;
}

//function to compare the value at midpoint with the search value

int comparer(int midpoint, int value, int values[])
{
int result = 0;
if(values[midpoint] == value)
result = 0;

else if(values[midpoint] > value)
result = 1;

else if(values[midpoint] < value)
result = -1;

return result;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int counter;

do
{
// implementing bubble sort by iterating over the entire array
for (int i = 0; i < n; i++)
{
counter = 0;
int temp = 0;
//stating the different cases
// Case: The value is bigger than the next one
if (values[i] > values[i + 1])
{
values[i] = temp;
values[i] = values[i + 1];
values[i + 1] = temp;
counter++;
}
}
}
while (counter != 0);
``````

}

It's because you pass the address of `midpoint` as the third parameter of `comparer()`, instead of `values[]`.

Try

``````int result = comparer(midpoint, value, values);
``````

``````int result = comparer(midpoint, value, &midpoint);
``````

## Edit

There are also some problems with your `sort()`.

It should be

``````if (values[i] > values[i + 1])
{
temp = values[i];
values[i] = values[i + 1];
values[i + 1] = temp;
counter++;
}
``````

``````if (values[i] > values[i + 1])
{
values[i] = temp;
values[i] = values[i + 1];
values[i + 1] = temp;
counter++;
}
``````

Also the

``````counter = 0;
``````

should be outside the for loop.

And lastly your for loop should run up to `n - 1`, not `n`. Consider the very last case where `i == n - 1`. Then you do

``````if (values[i] > values[i + 1])
``````

which is equal to

``````if (values[n - 1] > values[n])
``````

but there is no `values[n]`, so you will get a segfault, at best.

• Thanks for the advice. However, I'm still getting the same error message for certain tests that the check 50 does. eg :( finds 42 in {40,41,42} \ expected an exit code of 0, not 1 :) finds 42 in {41,42,43,44} Aug 23 '16 at 16:58
• Post the full code. Aug 23 '16 at 16:59
• edited the post to show the sort function as well Aug 23 '16 at 17:02
• check the edit. Aug 23 '16 at 17:19
• There is also probably a better way to write a bubble sort, but I will leave that to you. :) Happy coding! Aug 23 '16 at 17:20