# Bug in my Pset3 Binary Search helpers.c

When I run check50

``````check50 2015.fall.pset3.find helpers.c
``````

This is the terminal result

``````:) helpers.c exists
:) helpers.c compiles
:( finds 42 in {42,43,44}
\ expected an exit code of 0, not 1
:) finds 42 in {41,42,43}
:) finds 42 in {40,41,42}
:) finds 42 in {41,42,43,44}
:) finds 42 in {40,41,42,43}
:) finds 42 in {39,40,41,42}
:) doesn't find 42 in {39,40,41}
:) doesn't find 42 in {39,40,41,43}
``````

## Helpers.c

``````#include <cs50.h>

#include "helpers.h"

/**
* Returns true if value is in array of n values, else false.
*/

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

if (n < 0)
return false;

// Non-recursive binary search
// TODO: implement a searching algorithm
int min = 0;
int max = n;

// while length of the list > 0
while (min <= max)
{
// Look at the middle of the list
int middle = (min + max) / 2;

// if number found, return true
if (value == values[middle])
{
return true;
}
// else if number higher, search right
else if (value > middle)
{
min = middle + 1;
}

// else if number is lower, search left
else if (value < middle)
{
max = middle - 1;
}

}
return false;

}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
/**
*TODO: implement an O(n^2) sorting algorithm
* Bubble sort
* cycle through array
*/
for (int k = 0; k < n; k++)
{
/**
* Optmize,
* Check for no swaps
* int swaps = 0;
*/
for(int i = 0; i < n - 1 - k; i++)
{
if ( values[i] > values[i + 1])
{
int temp = values[i + 1];
values[i + 1] = values[i];
values[i] = temp;
}
}
}

return;

}
``````

Take a look at the following three lines of code and tell me what's different?

``````    if (value == values[middle])
else if (value > middle)
else if (value < middle)
``````

Why is the first one different from the last two? Are you really checking to see if value is greater or less than the value of the array's index rather than an array element's contents?

Next, there's this:

``````int max = n;
``````

N is the number of elements in the array, while max represents the maximum index that can be used in an array. I.E., if n=4, then max should be 3, not 4, because 'value[4]' doesn't exist when n=4.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

• Thanks, @cliff-b, Worked like a charm! ;) I understand your pov for n but both: `max = n; max = n - 1;` worked without any problems! Mar 2 '16 at 22:38