C 標(biāo)準(zhǔn)庫 - <stdlib.h>
C 庫函數(shù) void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) 對(duì) nitems 對(duì)象的數(shù)組執(zhí)行二分查找,base 指向進(jìn)行查找的數(shù)組,key 指向要查找的元素,size 指定數(shù)組中每個(gè)元素的大小。
數(shù)組的內(nèi)容應(yīng)根據(jù) compar 所對(duì)應(yīng)的比較函數(shù)升序排序。
下面是 bsearch() 函數(shù)的聲明。
void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))
如果查找成功,該函數(shù)返回一個(gè)指向數(shù)組中匹配元素的指針,否則返回空指針。.
下面的示例演示了 bsearch() 函數(shù)的用法。
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int values[] = { 5, 20, 29, 32, 63 };
int main ()
{
int *item;
int key = 32;
/* 使用 bsearch() 在數(shù)組中查找值 32 */
item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
if( item != NULL )
{
printf("Found item = %d\n", *item);
}
else
{
printf("Item = %d could not be found\n", *item);
}
return(0);
}讓我們編譯并運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
Found item = 32