C语言标准库函数 bsearch 详解

#include < stdlib.h> void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
参数:第一个:要查找的关键字。第二个:要查找的 数组。第三个:指定 数组中元素的数目。第四个:每个元素的长度(以 字符为单位)。第五个:指向比较函数的 指针
功能: 函数用折半查找法在从 数组元素buf[0]到buf[num-1] 匹配参数key。如果函数compare 的第一个参数小于第二个参数,返回负值;如果等于返回零值;如果大于返回正值。 数组buf 中的元素应以升序排列。函数bsearch()的返回值是指向匹配项,如果没有发现匹配项,返回NULL

1)数组buf 中的元素应以升序排列。如果函数compare 的第一个参数(输入的值)小于第二个参数(数组元素),返回负值;如果等于返回零值;如果大于返回正值。
2)数组buf 中的元素应以降序排列。如果函数compare 的第一个参数大于第二个参数,返回负值;如果等于返回零值;如果小于返回正值。

key
        Pointer to the object that serves as key for the search, type-casted as a void*.
base
        Pointer to the first object of the array where the search is performed, type-casted as a void*.
num
        Number of elements in the array pointed by base.
size
        Size in bytes of each element in the array.
comparator
        Function that compares two elements. The function shall follow this prototype:

        int comparator ( const void * pkey, const void * pelem ); 
        The function must accept two parameters: the first one pointing to the key object, and the second one to an

        element of the array, both type-casted as void*. The function should cast the parameters back to some data

        type and compare them.

       The return value of this function should represent whether the value pointed by pkey is considered less than,

       equal, or grater than the value pointed by pelem by returning, respectively, a negative value, zero or a positive

       value.

       For types that support regular comparison operators, a general comparator function may look like:



C语言中可以用bsearch()实现二分查找。同qsort()一样,bsearch()也包含在<stdlib.h>库中,且同样要自定义比较子函数。其原型如下:
 

void *bsearch(const void *keyconst void *base, size_t nmemsize_t size, int (*comp)(const void *, const void *));

key指向所要查找的元素,base指向进行查找的数组,nmem为查找长度,一般为数组长度,size为每个元素所占的字节数,一般用sizeof(...)表示,comp指向比较子函数,它定义比较的规则。需要注意的是,数据必须是经过预先排序的,而排序的规则要和comp所指向比较子函数的规则相同。如果查找成功则返回数组中匹配元素的地址,反之则返回空。对于有多于一个的元素匹配成功的情况,bsearch()未定义返回哪一个。

例:

#include <stdio.h>
#include <stdlib.h>

#define NUM 8

int compare(const void *p, const void *q)
{
    return (*(int *)- *(int *)q);
}

int main(int argc, char *argv[])
{
    int array[NUM] = {9, 2, 7, 11, 3, 87, 34, 6};
    int key = 3;
    int *p;

    
    qsort(array, NUM, sizeof(int), compare);
    p = (int *)bsearch(&key, array, NUM, sizeof(int), compare);

    (== NULL) ? puts("not found") : puts("found");

    return 0;
}

结果如下:

found








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值