bsearch

王朝百科·作者佚名  2010-01-15  
宽屏版  字体: |||超大  

函数名: bsearch

功 能: 二分法搜索

用 法: void *bsearch(const void *key, const void *base, size_t *nelem, size_t width, int(*fcmp)(const void *, const *));

语法:

#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

程序例:

#include<stdlib.h>

#include<stdio.h>

#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))

int numarray[] = {123, 145, 512, 627, 800, 933};

int numeric (const int *p1, const int *p2){

return(*p1 - *p2);

}

int lookup(int key){

int *itemptr;

/* The cast of (int(*)(const void *,const void*))

is needed to avoid a type mismatch error at

compile time */

itemptr = (int *)bsearch (&amp;key, numarray, NELEMS(numarray),

sizeof(int), (int(*)(const void *,const void *))numeric);

return (itemptr != NULL);

}

int main(void){

if (lookup(512)){

printf("512 is in the table.

");

}

else{

printf("512 isn't in the table.

");

}

return 0;

}

 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝百科 版权所有