I'm currently struggling with the binary search in pset 3 and I think I already found out how to implement it. I just really can't understand why, after return res;
, the program does not leave the bysearch
function.
When I run gdb using, for example, the value 4
and the haystack: 1, 2, 3, 4, 5, 6, 7, 8, 9;
when it reaches the line "return res", instead of exiting the function, the program calls the bysearch
function again using other values of min and max.
int bysearch(int value, int values[],int min,int max)
{
int res = 0;
int midpoint;
if(max < min)
{
res = 0;
}
else
{
midpoint = findmid(min, max);
if(values[midpoint] < value)
{
bysearch(value, values, midpoint+1, max);
}
else if(values[midpoint] > value)
{
bysearch(value, values, mid, midpoint-1);
}
else
{
res = 1;
}
}
return res;
}
This is what happens, gdb.
int
rather than abool
?findmid()
function work? What's the formula for finding the middle index?