1

有谁知道标准的二分查找功能是如何实现的?

这是原型。

void * bsearch (const void*, const void*, size_t, size_t, int (*) (const void *, const void *) );

我真的很好奇他们如何使用 void 指针。

4

3 回答 3

3

我假设您有兴趣了解void *指针是如何使用的bsearch,而不是实际的二进制搜索算法本身。的原型bsearch是:

void *bsearch(const void *key, const void *base,
    size_t nmemb, size_t size,
    int (*compar)(const void *, const void *));

这里void *使用 ,以便可以搜索任意类型。指针的解释由(用户提供的)compar函数完成。

由于指针base指向数组的开头,并且数组的元素保证是连续的,bsearch因此可以通过指针运算得到void *指向数组中任何元素的指针。nmemb例如,要获取指向数组中第五个元素的指针(假设nmemb >= 5):

unsigned char *base_p = base;
size_t n = 5;
/* Go 5 elements after base */
unsigned char *curr = base_p + size*n;
/* curr now points to the 5th element of the array.
   Moreover, we can pass curr as the first or the second parameter
   to 'compar', because of implicit and legal conversion of curr to void *
   in the call */

在上面的代码片段中,我们不能size*n直接添加到,base因为它是 type ,并且没有定义void *算术 on 。void *

于 2010-01-13T09:05:49.960 回答
1

请参阅bsearch @Google 的代码搜索 以了解bsearch.

于 2010-01-03T03:07:51.700 回答
-1

看源头。如果您有 VS Standard 或更高版本,请参阅:

C:\Program Files\Microsoft Visual Studio 8\VC\crt\src\bsearch.c

于 2010-01-03T03:03:16.873 回答