二分法搜索bsearch使用举例

本文介绍了一个使用C语言实现的数组查找示例,通过bsearch函数和自定义比较函数完成对预设整数数组的二分搜索,以判断指定数值是否存在于数组中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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 = bsearch (&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./n");

   else

      printf("512 isn't in the table./n");

 

   return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值