C语言中库函数自带的查找函数bsearch
2014-10-06 19:46
357 查看
之前查看qsort函数的时候无意间看到了一个C语言内置的查找函数bsearch.
[b]#include <stdlib.h> [/b]
[b]void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
功能:[/b]函数用折半查找法在从数组元素buf[0]到buf[num-1] 匹配参数key。如果函数compare 的第一个参数小于第二个参数,返回负值;如果等于返回零值;如果大于返回正值。数组buf 中的元素应以升序排列。函数bsearch()的返回值是指向匹配项,如果没有发现匹配项,返回NULL。
下面是我的测试代码:
[b]#include <stdlib.h> [/b]
[b]void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
功能:[/b]函数用折半查找法在从数组元素buf[0]到buf[num-1] 匹配参数key。如果函数compare 的第一个参数小于第二个参数,返回负值;如果等于返回零值;如果大于返回正值。数组buf 中的元素应以升序排列。函数bsearch()的返回值是指向匹配项,如果没有发现匹配项,返回NULL。
下面是我的测试代码:
#include <stdio.h> #include <stdlib.h> #include <assert.h> int compare(const void *value1, const void *value2); int main(int argc, char const *argv[]) { int size = 0; scanf("%d", &size); assert(size > 0); int *array = (int *)calloc(size, sizeof(int)); int i = 0; for (i = 0; i < size; ++i) { scanf("%d", &array[i]); } //由于二分查找需要在查找数组有序的情况下才能正确的工作, //所以这里先调用qsort函数进行排序 qsort(array, size, sizeof(int), compare); int key = 0; printf("input the key:"); scanf("%d", &key); int *pointer = (int *) bsearch(&key, array, size, sizeof(int), compare); if (pointer != NULL) { printf("find the key: %d\n", *pointer); // printf("pointer: %d\n", pointer); } else { printf("cannot find the key: %d\n", key); } free(array); return 0; } int compare(const void *value1, const void *value2) { return *(int *)value1 - *(int *)value2; }
相关文章推荐
- C语言中库函数自带的排序函数qsort
- C语言中用bsearch()实现查找操作
- C语言调用库函数实现二分查找
- 二维数组中的查找及C语言中二维数组做函数参数
- C语言——字符串查找字符的两个函数
- C 语言中自定义类型排序函数qsort以及相应的二分法查找函数bsearch
- 二分法——查找、排序以及库函数bsearch的用法
- C语言index()函数:查找字符串并返回首次出现的位置
- 【c语言】模拟实现库函数的atof函数
- C语言rindex()函数:查找字符串并返回最后一次出现的位置
- C语言的字符串查找函数
- 二分法——查找、排序以及库函数bsearch的用法
- C语言 函数的简单使用(库函数和自定义函数)
- 二分法——查找、排序以及库函数bsearch的用法
- 关于C语言自带的错误机制,可选的提示错误函数perror(),strerror(errno),个人测试结果
- MATLAB 自带函数源代码的查找
- C语言调用库函数实现二分查找
- 二分查找函数bsearch与排序函数qsort(两个好基友)
- 快速排序qsort()函数和二分查找bsearch()函数
- C语言子串查找函数