so as the title suggests I am having some trouble with my implementation of binary search. So based on the logic shown in the lecture, I think my implementation is fine, indeed it works for the cases where the value is inside the array, however the case where the value is not in the array, it hangs and says the value cannot be found. Sorting is fine, its just the case where the value is not in the array that it fails.
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
int max = n-1;
int min = 0;
if(n < 0)
{
return false;
}
while(n > 0)
{
int middle = ((max)+min)/2;
if(values[middle]==value)
{
return true;
}
else if(values[middle]> value)
{
// middle = ((middle-1)+min)/2;
max = middle - 1;
}
else if(values[middle] < value)
{
min = middle+1;
}
}
return false;
}
THE OUTPUT:
:) helpers.c exists
:) helpers.c compiles
:) finds 42 in {42,43,44}
:) 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}
\ killed by server
:( doesn't find 42 in {39,40,41,43}
\ killed by server**
:) finds 42 in {42,40,39,41}
https://sandbox.cs50.net/checks/586c0fdc7e414d5ebced4f29e20c9c33