#C 语言标准库函数 bsearch_s
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdlib.h>
void *bsearch_s(const void *key, const void *base, rsize_t nmemb, rsize_t size,
int (*compar)(const void *, const void *, void *), void *context);
说明
在已排序的数组中用二分搜索查找与 key 等价的元素。
数组须按与本次比较相容的顺序排列。比较回调收到的第一个参数是查找键。C23 的类型通用调用保留被查找数组的 const 限定,上述原型是普通函数版本。元素数和大小须在 RSIZE_MAX 范围内,非空数组需要有效的数组指针和比较函数。
C11 附录 K 可选接口。需要定义 __STDC_LIB_EXT1__ 的实现,并在包含相关头文件前将 __STDC_WANT_LIB_EXT1__ 定义为 1。
参数
key- 指向要查找的对象。base- 元素连续存储的数组起始地址。nmemb- 数组元素数。size- 每个元素的字节数。compar- 比较回调,按第一个对象小于、等于或大于第二个对象返回负数、零或正数。context- 透传给比较回调的用户上下文,可以是空指针。
返回值
- 找到时返回元素地址,重复元素中选哪一个由实现决定。找不到时返回空指针。违反运行时约束时也返回空指针。
#示例
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdlib.h>
static int compare_ints(const void *a, const void *b, void *context)
{
(void)context;
int first = *(const int *)a;
int second = *(const int *)b;
return (first > second) - (first < second);
}
int main(void)
{
const int values[] = {1, 3, 7, 9};
int key = 7;
const int *found = bsearch_s(&key, values, 4, sizeof values[0], compare_ints, NULL);
return found == NULL || *found != key;
}