Reputation: 55
I am trying to binary search a string from a struct of arrays. I keep getting a segmentation fault or an infinite loop. I was wondering what I am doing wrong.
int binsearch(struct person d[25], int low_int, int high_int, char search[15])
{
int mid_int;
printf(".");
mid_int = ((high_int - low_int)/2);
mid_int = mid_int + low_int;
if(strcmp(search, d[mid_int].name) == 0)
return mid_int;
if(low_int > high_int)
return -1;
else if(strcmp(search, d[mid_int].name) > 0)
{
binsearch(d, mid_int+1, high_int, search);
}
else
{
binsearch(d, low_int, mid_int-1, search);
}
}
Whenever I add in the "mid_int = mid_int + low_int" it gives me a straight segmentation error. Where as when I take it away it goes on an infinite loop printing "....." then resulting in a segmentation fault (the periods are to show how many loops it takes for the search).
Upvotes: 0
Views: 61
Reputation: 25752
First of all you will have to use the return
keyword on the recursive binsearch()
calls if you want to get any result out of them.
Then make the if if(low_int > high_int)
check before accessing the struct array so you don't access elements out of bounds.
Assuming you are calling the function with valid parameters, the code should work.
binsearch( d , 0 , d_size-1 , "Search" ) ;
Note that the the function definition:
int binsearch(struct person d[25], int low_int, int high_int, char search[15])
is equivalent to
int binsearch(struct person d[], int low_int, int high_int, char search[])
Those sizes 25 and 15 don't do anything in this case. You will have to pass the size of your arrays. This is already handled by low_int
, high_int
for d
and search
should be nul terminated since it is a string.
Upvotes: 2