bsearch函数

Bsearch函数详解

函数名: bsearch

  功 能: 二分法搜索

  用 法: void *bsearch(const void *key, const void *base,size_t nelem, size_t width, int(*fcmp)(const void *, const *));

  语法:

  #include <stdlib.h>void *bsearch( const void *key, const void *buf, size_t num, size_t size, int(*compare)(const void *, const void *) );

参数:第一个:要查找的关键字。第二个:要查找的数组。第三个:指定数组中元素的数目。第四个:每个元素的长度(以字符为单位)。第五个:指向比较函数的指针。

解释一下参数

key 指向要查找的元素

base 指向进行查找的数组

num 数组中元素的个数

size 数组中每个元素的大小,一般用sizeof()表示

cmp 比较两个元素的函数,定义比较规则。需要注意的是,查找数组必须是经过预先排序的,而排序的规则要和比较子函数cmp的规则相同。

因为使用bsearch函数要求数组预先排好序,所以该函数通常和快速排序函数(qsort)一起使用。

 

功能: 函数用折半查找法在从数组元素buf[0]到buf[num-1]匹配参数key。如果函数compare 的第一个参数小于第二个参数,返回负值;如果等于返回零值;如果大于返回正值。数组buf 中的元素应以升序排列。函数bsearch()的返回值是指向匹配项,如果没有发现匹配项,返回NULL

程序例:

#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*)) isneeded to avoid a type mismatch error at compile time

  itemptr = (int *)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;

  }

  例2:

  对一个字符数组进行排序并查找指定字符串的例子:

  #include <stdlib.h>

  #include <stdio.h>

  #include <string.h>

  #define LENGTH(x) sizeof(x)/sizeof(x[0])

  /**输出数组元素

  *\param arr:指向数组的指针

  *\param len:数组元素的个数

  */

  void print(char (*arr)[10],int len)

  {

  int i;

  for (i=0;i<len;i++)

  {

  printf("%s ",arr[i]);

  }

  printf("\n");

  }

  int main()

  {

  chararr[][10]={"bac","bca","abc","acb","cba","cab"};/* 定义二维字符数组*/

  char *key="bca";/* 要查找的字符串*/

  char *ptr=NULL; /* 字符指针*/

  // 输出未排序时字符数组的内容

  printf("before qsort :");

  print(arr,LENGTH(arr));

  /* 使用qsort对字符数组排序*/

  qsort((void *)arr,LENGTH(arr),sizeof(arr[0]),(int(*)(const void *,const void *))strcmp);

  /* 输出排序后字符数组的内容*/

  printf("after qsort :");

  print(arr,LENGTH(arr));

  /* 采用二分查找查找指定字符*/

  ptr=(char *)bsearch(key,arr,LENGTH(arr),sizeof(arr[0]),(int(*)(const void *,const void *))strcmp);

  if (ptr)

  { /* 找到*/

  printf("%s is in the array\n",key);

  }

  else/* 没找到*/

  {

  printf("%s isn't in the array\n",key);

  }

  return 0;

  }

具体应用:

POJ 2503 Babelfish C语言版

200963 21:52Slyar发表评论阅读评论

文章作者:Slyar 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

快排qsort() + 二分查找bsearch()

Description

You have just moved fromWaterloo to a big city. The people here speak an incomprehensible dialect of aforeign language. Fortunately, you have a dictionary to help you understandthem.

Input

Input consists of up to100,000 dictionary entries, followed by a blank line, followed by a message ofup to 100,000 words. Each dictionary entry is a line containing an Englishword, followed by a space and a foreign language word. No foreign word appearsmore than once in the dictionary. The message is a sequence of words in theforeign language, one word on each line. Each word in the input is a sequenceof at most 10 lowercase letters.

Output

Output is the messagetranslated to English, one word per line. Foreign words not in the dictionaryshould be translated as "eh".

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh
loops

Slyar:题目大意很简单,就是给你字典的对应信息,然后给你查询条件要求你输出字典查询结果,如果字符串没有在字典中则输出"eh"

恩,学到了一个新的函数bsearch(),可以进行二分查找。先对字典使用qsort排序然后再使用bsearch()查找字符串即可。

还学到了一个输入函数sscanf(),可以从一个字符串中读取内容,格式如下

sscanf (string str, stringformat [, string var1...])



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
typedefstruct
{
          char en[11];
          char fn[11];
}dict;
 
dict a[100001];
 
/* 定义qsort比较函数 */
int q_cmp(constvoid* a,constvoid*b)
{
    return strcmp(((dict*)a)->fn,((dict*)b)->fn);
}
 
/* 定义bsearch比较函数 */
int b_cmp(constvoid* a,constvoid* b)
{
    return strcmp((char*)a,((dict*)b)->fn);
}
 
int main()
{
          char str[30];
          int i, sign;
          dict *p;
 
          i =0;
          /* 查询标记记为"未开始" */
          sign =1;
          /* 读取字符串直到文件结束 */
          while(gets(str))
          {
                    /* 遇到空行则开始排序字典 */
                    if(str[0]=='\0')
                    {
                               /* 查询标记记为"开始" */
                              sign =0;
                               qsort(a, i,sizeof(dict), q_cmp);
                               continue;
                    }
                    /* 查询未开始时读取字典信息 */
                    if(sign)
                    {
                               /* 使用sscanf从str中读取查询要求 */
                               sscanf(str,"%s %s", a[i].en, a[i].fn);
                               i++;
                    }
                    /* 查询开始时进行查询 */
                    else
                    {
                               /* 二分查找指定字符串 */
                               p =(dict*) bsearch(str, a, i,sizeof(dict), b_cmp);
                               /* 找到则输出结果 */
                               if(p)
                               {
                                         puts(p->en);
                               }
                               /* 找不到输出"eh" */
                               else
                               {
                                         puts("eh");
                               }
                    }
          }
          //system("pause");
          return0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值