运用Stdlib.h中bsearch函数查找一个已排序的记录数组

//C++,WinXP操作系统,,VC6.0下编译通过。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct person
{
 char last[16];
 char first[11];
 char phone[13];
 int age;
};

static int comp(const void*, const void*);

main()
{
 int i;
 struct person *p;
 
 static struct person key={"","","555-1965",0};

 static struct person people[] =
 {{"ford","henry","555-1903",98},
  {"lincoln","abraham","555-1865",161},
  {"ford","edsel","555-1965",53},
 {"trump","donald","555-1988",49}};

 //排序
 qsort(people,4,sizeof people[0],comp);
   
 //查找
 p=(struct person *)bsearch(&key,people,4,sizeof people[0],comp);
 if (p != NULL)
 {
  printf(
   "%s,%s,%s,%d/n",
   p->last,
   p->first,
   p->phone,
   p->age
   );
 }
 else
  puts("Not found");

 return 0;
}

/*比较函数,关键值是电话号码字段*/
static int comp(const void *x,const void *y)
{
 struct person *p1=(struct person *)x;
 struct person *p2=(struct person *)y;

 return strcmp(p1->phone,p2->phone);
}

 

 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值