I tried to return the right index of an array element with a recursive binary search algorithm, however it returns just the index of the portion taken into consideration.
For example, if the list is composed by the name "Grant", "Anthony" and "Samuel", the algorithm will return the value 0 if I search for "Samuel".
short binarySearch(person key, person list[], short n)
{
size_t mid;
if(n == 0)
return -1;
mid = (n-1)/2;
if(strcmp(key.name, list[mid].name) == 0 && strcmp(key.surname, list[mid].surname) == 0)
return mid;
else if(strcmp(key.name, list[mid].name) < 0)
return binarySearch(key, list, mid);
else
return binarySearch(key, list+mid+1, n-mid-1);
}
UPDATE:
I solved in this way (thanks to @mevets and @selbie):
int binarySearch(person key, person *list, size_t n)
{
int cmp = 0, result;
size_t mid;
if(n == 0)
return -1;
mid = (n - 1) / 2;
cmp = strcmp(key.name, list[mid].name);
if(cmp == 0)
{
cmp = strcmp(key.surname, list[mid].surname);
if(cmp == 0)
return mid;
}
if(cmp < 0)
return binarySearch(key, list, mid);
result = binarySearch(key, list+mid+1, n-mid-1);
if(result == -1)
return -1;
return 1 + mid + result;
}
nameproperty value, but differentsurnamevalue, you could potentially recurse the wrong subarray. Consider the array[{"bob", "anderson"}, {"bob", "jones"}, {"bob, "zumuda"}]. And then you search for"bob anderson".