I would be really grateful if someone could offer me a hint as to where I'm going wrong with this - I've been stuck for a couple of days now. When I work through the code step by step on paper it seems fine & logical, but obviously something's not right with my search function.
Please excuse my ugly code! A point in the right direction would be wonderful!
:) 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}
\ expected an exit code of 0, not 1
:( finds 42 in {41,42,43,44}
\ expected an exit code of 0, not 1
:) finds 42 in {40,41,42,43}
:( finds 42 in {39,40,41,42}
\ expected an exit code of 0, not 1
:) doesn't find 42 in {39,40,41}
:) doesn't find 42 in {39,40,41,43}
https://sandbox.cs50.net/c…/595ffa008b4a4ef3a10192819d0dc6a6
int findmid(int start, int end) //function to find midpoint
{
int mid = (start + end)/2;
return mid;
}
bool binarysearch(int value, int values[], int n, int start, int end) //my binary search function
{
if (start > end) // if end < start we've gone too far, the value isn't there.
{
return false; //returns false.
}
int mid = findmid(start, end); //mid is mid-point of search area
if (values[mid] == value) //if the int at mid position is the same as value, we've found it! WHY DOESN'T THIS WORK?
{
return true;//returns true
}
if (values[mid] > value) //if the int at mid position in array is more than the value we're looking for
{
binarysearch(value, values, n, start, mid - 1); //sets end of search area to value to left of mid, calls binarysearch function recursively
}
else if (values[mid] < value) // if the int at mid position is less than the value we're looking for
{
binarysearch(value, values, n, mid + 1, end); //sets start of search area to value to right of mid, calls binarysearch function recursively
}
return false; //returns false
}
bool search(int value, int values[], int n) //this works, don't change it
{
int start = 0; //sets start of search area
int end = n; //sets end of search area to size of array
if (binarysearch(value, values, n, start, end))//calls binarysearch function, passes search arguments plus start and end and checks if it returns true
{
return true;
}
else
{
return false;
}
}