I am solving "Programming Pearls" exercises. 4.11 say:
Write and prove the correctness of a recursive binary search function in C or C++ with this declaration:
int binarysearch(DataType x[], int n);
Use this function alone; do not call any other recursive function.
I came up with:
int bsearch_rec_array_only(int key, int* arr, int n)
{
int mid;
if (n < 0)
return -1;
mid = n / 2;
if (arr[mid] == key)
return (int) ((size_t) arr + mid * sizeof(*arr));
else if (arr[mid] < key)
return bsearch_rec_array_only(key, arr + mid + 1, n - mid - 1);
else
return bsearch_rec_array_only(key, arr, mid - 1);
}
However - there is problem. I return the offset including array address because otherwise how to know the relative offset of the element to original array?
So I need this wrapper:
int bsearch_array_only_wrap(int key, int* arr, int n)
{
int offset;
if (n == 0)
return -1;
offset = bsearch_rec_array_only(key, arr, n);
if (offset == -1)
return -1;
else
return (offset - (int) arr) / sizeof(*arr);
}
It's not recursive - it just calls bsearch_rec_array_only
and computes offset.
But this seems complicated. Can you find a better solution?