我正在解决“编程珍珠”练习。 4.11说:
写下并证明a的正确性 C中的递归二进制搜索函数 或带有此声明的C ++:
int binarysearch(DataType x [],int n);
单独使用此功能;不要打电话 任何其他递归函数。
我想出了:
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);
}
然而 - 有问题。我返回包含数组地址的偏移量,否则如何知道元素与原始数组的相对偏移量?
所以我需要这个包装器:
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);
}
它不是递归的 - 它只是调用bsearch_rec_array_only
并计算偏移量。
但这似乎很复杂。你能找到更好的解决方案吗?
答案 0 :(得分:2)
您的问题是代码不会从数组的开头返回元素的偏移量,而是将指针强制转换为int。您使用演员表的事实应该会告诉您代码中存在错误。
尝试返回偏移量。像这样:
if (arr[mid] == key)
return mid;
else if (arr[mid] < key) {
int i = bsearch_rec_array_only(key, arr + mid + 1, n - mid - 1);
return (i != -1) ? i + mid + 1 : -1;
} else
return bsearch_rec_array_only(key, arr, mid - 1);
答案 1 :(得分:0)
这是正确答案:
// Recursive binary search
int bsearch(int key, int * arr, int n)
{
if (n == 0)
{
return -1;
}
int m = n / 2;
int found;
if (arr[m] == key)
{
found = m;
}
else if (arr[m] < key)
{
// Upper half. We'll search in upper half of the current array with new length
// of the upper half.
found = bsearch(key, arr + m + 1, n - m - 1);
if (found != -1)
{
// Since we've found a key, need to offset it to make valid in the
// current search scope
found += m + 1;
}
}
else
{
// Lower half, there is no need to offset the array.
// New array length is equal to the current middle point.
found = bsearch(key, arr, m);
}
assert(found == -1 || (found >= 0 && found < n && arr[found] == key));
return found;
}