在初学写程序时,特别是刚开始接触数据结构时,基本都是在查找;
各种排序,其实都是在为查找做准备。
=============================
今天我们来看看关于c语言中自带的一个二分法搜索函数bsearch
通过这个函数可以简单的认识到二分法搜索的一些内在的原理,以及发散一点其他搜索方法的东西。
=============================
首先,介绍这个函数
函数原型:
- void *bsearch(const void *key, const void *base, size_t *nelem,
- size_t width, int(*fcmp)(const void *, const *))
头文件:#include<stdlib.h>
参数介绍:
参数key指向要查找的关键字的指针;
base指向从小到大的次序存放元素的查找表;
nelem指定查找表元素的个数;
width指定查找表中每个元素的字节数;
int(*fcmp)(const void *, const *)为由用户提供的比较函数。
=================================
首先,给出一个简单的比较函数
- {
- if(*a<*b)
- return -1;
- else if(*a>*b)
- return 1;
- else
- return 0;
- }
然后在main函数中我们只需要将各种参数按照顺序填进函数中调用就可以了。
像这样……
- int search[10]={1,3,6,7,10,11,13,19,28,56}
- int a=13,*p,i;
- p=(int *)bsearch(&a, search,10, sizeof(int),CMP);