#include <iostream>
#include <cstdlib>
using namespace std;
int my_compare( const int *first, const int *second )
{
return (*first - *second);
}
int main( void )
{
const int buf[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1500, 1700, 2002};
const size_t size = sizeof (buf) / sizeof (*buf);
cout << "size = " << size << endl;
int cpp = 2002;
void *pTest = bsearch( &cpp, buf, size, sizeof (int),
(int(*)(const void *,const void *))my_compare );
if (NULL == pTest)
{
cout << "not find" << endl;
}
else
{
cout << "find" << endl;
}
system( "PAUSE" );
return EXIT_SUCCESS;
}
/*-------------------
#include <cstdlib>
/函数原型:
void *bsearch( const void *key,
const void *buf,
size_t num,
size_t size,
int (*compare)(const void *, const void *) );
/文档说明:
The bsearch() function searches buf[0] to buf[num-1] for an item that matches key,
using a binary search.
bsearch()函数在buf[0]到buf[num-1]之间使用二分查找的方法查找与关键字key相匹配的item,
The function compare should return negative if
its first argument is less than its second,
zero if equal,
and positive if greater.
比较函数有三种返回值:
当比较函数的第一个参数小于第二个参数时,返回负数;
当第一个参数等于第二个参数时每回零;
当第一个参数大于第二个参数时返回正数;
The items in the array buf should be in ascending order.
要求数组buf中的item是升序排列好的。
The return value of bsearch() is a pointer to the matching item,
or NULL if none is found.
如果找到了与关键字key匹配的item,bsearch()函数返回指向这个item的指针。
如果没有找到,bsearch()函数返回NULL。
/程序运行结果:
size = 12
find
请按任意键继续. . .
---------------------------------*/
C库中的二分法搜索函数
最新推荐文章于 2022-07-04 09:17:56 发布