# My binary sort function cannot find the needle in the haystack. Can anyone see the bug in this code?

I am testing by using `./generate 1000 50 | ./find 127`. The needle should be found but isn't.

``````#include <stdio.h>
#include <cs50.h>
#include <string.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<1)
{
return false;
}
// TODO: implement a detecting algorithm, if found end loop
int max=n-1;
int min=0;
while ((max-min)>0)
{
int mid = ((min+max)/2);
if (values[mid]==value)
return true;
if (values[mid]<value)
min = mid+1;
if (values[mid]>value)
max = mid-1;
}
}
``````

If i'm not wrong, your implementation fails to reach the base case. If you have the list {1,3,5} and are triyng to find 5, for example, your algorithm will do this:

``````max = 2;
min = 0;
max-min = 2, greater than 0, so
mid = 1
values[1]  < value, so
min = 2
``````

at this point, the condition for your while loop is reached, 2-2=0, so it will not iterate again, failing to check if values[2] == value.

• Hmm I just corrected 'while ((max-min)>0)' to be 'while ((max-min)>=0)' but it is still not finding the needle. Oct 30, 2015 at 22:44

Perhaps it would work if you simply changed the condition of the while loop from:

``````while ((max-min)>0)
``````

To:

``````while (min <= max + 1)
``````

I copied your code, made the change, tested it out, and it found the needle with no problem.