|
楼主 |
发表于 2004-5-8 17:17:03
|
显示全部楼层
<>函数名: bsearch
功 能: 二分法搜索
用 法: void *bsearch(const void *key, const void *base, size_t *nelem,
size_t width, int(*fcmp)(const void *, const *));
程序例: <>#include <stdlib.h>
#include <stdio.h> <>#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) <P>int numarray[] = {123, 145, 512, 627, 800, 933}; <P>int numeric (const int *p1, const int *p2)
{
return(*p1 - *p2);
} <P>int lookup(int key)
{
int *itemptr; <P> /* The cast of (int(*)(const void *,const void*))
is needed to avoid a type mismatch error at
compile time */
itemptr = bsearch (&key, numarray, NELEMS(numarray),
sizeof(int), (int(*)(const void *,const void *))numeric);
return (itemptr != NULL);
} <P>int main(void)
{
if (lookup(512))
printf("512 is in the table.\n");
else
printf("512 isn't in the table.\n"); <P> return 0;
}
</P> |
|