二分法bsearch函数使用简单介绍

来源:互联网 发布:前端框架ajax取数据 编辑:程序博客网 时间:2024/04/28 03:22

在项目中经常使用到这个函数,方便简单。比如产品本身有产品ID,产品属性,生效时间,失效时间,订购时间。而产品的价格在另外一个表里,比如这个表里有这些字段,产品ID,定价计划ID,定价计划类型,产品价格。当用户订购这个产品的时候,就需要获取这个产品的价格进行批价扣帐,就需要用产品ID获取产品对应的定价计划ID,然后根据定价计划ID获取产品价格,这个时候就用到很多查找的方法。

 

bsearch函数原形为

void *bsearch(const void *key, const void *base, size_t nmem, size_t size, int (*comp)(const void *, const void *));

key为查找的关键字,

base为被查找的数组,数组必须是从小到大排序

nmem为被查找数组的个数

size为数组元素的字节大小

comp函数为比较规则或者说查找规则

 

弄个简单例子和大家分享下,为了简单,例子和以上的描述不一样:

#include "stdafx.h"
#include<string>


#define NUM    5

typedef struct
{
    char stu_id[5];
    char stu_name[20];
    char stu_class[3];
    char record[10];
}  STU_TAB;


int CompareFunc(const char *a1 , const STU_TAB *a2 )
{  
         return( strcmp( a1 ,a2->stu_id )); 
}


bool Find_Record(char* szStuID,STU_TAB* pStuTable)
{
   
    STU_TAB* pStuInformation;
    pStuInformation = (STU_TAB *)bsearch(szStuID ,
               pStuTable, NUM,
               sizeof(STU_TAB),
               (int(*)(const void *,const void *))CompareFunc);

       if (pStuInformation)
      {
            return true;
      }

      return false;

}

int main(int argc, char* argv[])
{
         STU_TAB std[6];

          strcpy(std[0].stu_id,"0001");
          strcpy(std[0].stu_class,"C01");
          strcpy(std[0].stu_name,"ouxiong");
          strcpy(std[0].record,"98");

          strcpy(std[1].stu_id,"0002");
           strcpy(std[1].stu_class,"C02");
           strcpy(std[1].stu_name,"ouxiong");
          strcpy(std[1].record,"98");

           strcpy(std[2].stu_id,"0003");
           strcpy(std[2].stu_class,"C03");
           strcpy(std[2].stu_name,"ouxiong");
           strcpy(std[2].record,"98");

           strcpy(std[3].stu_id,"0004");
            strcpy(std[3].stu_class,"C04");
            strcpy(std[3].stu_name,"ouxiong");
            strcpy(std[3].record,"98");

            strcpy(std[4].stu_id,"0005");
            strcpy(std[4].stu_class,"C05");
            strcpy(std[4].stu_name,"ouxiong");
            strcpy(std[4].record,"98");

            bool bFind = Find_Record("0004",std);

           if (bFind)
           {
                  printf("Find the record");
           }


           return 0;
}