C库中的二分法搜索函数

#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
请按任意键继续. . .
---------------------------------*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值