bsearch的用法

bsearch(二分法查找)

原型:

void* bsearch (const void* key, const void* base, size_t num, size_t size, int (*compar)(const void*,const void*));

基本定义:

在有序表中,取中间记录作为比较对象,若给定值与中间记录的值相等,则查找成功;若给定值小于中间记录的值,则在中间记录的左半区继续查找;若给定值大于中间记录的值,则在中间记录的右半区继续查找。不断重复上述过程,直到找到为止。

限制条件:

在查找需要对列表进行sort,使列表变为有序状态。

Parameters

key-pointer to the element to search for(要搜索元素的指针)
ptr-pointer to the array to examine(要检查的数组的指针)
count-number of element in the array(数组中的元素数量)
size-size of each element in the array in bytes(数组中每个元素的大小)
comp-comparison function which returns ​a negative integer value if the first argument is less than the second, a positive integer value if the first argument is greater than the second and zero if the arguments are equivalent. key is passed as the first argument, an element from the array as the second.(比较函数,如果第一个参数小于第二个参数,则返回负整数值;如果第一个参数大于第二个参数,则返回正整数值;如果参数相等,则返回零。键作为第一个参数传递,数组中的元素作为第二个参数传递。)

The signature of the comparison function should be equivalent to the following:

 int cmp(const void *a, const void *b);

The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.(该函数不得修改传递给它的对象,并且在调用相同对象时,无论它们在数组中的位置如何,都必须返回一致的结果。)

测试代码

#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std;

int compare(const void *ap, const void *bp)
{
	const int *a = (int *)ap;
	const int *b = (int *)bp;
	if (*a < *b)
		return -1;
	else if (*a > *b)
		return 1;
	else
		return 0;
}

int main(int argc, char **argv)
{
	const int ARR_SIZE = 8;
	int arr[ARR_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8 };

	int key1 = 4;
	int *p1 = (int *)std::bsearch(&key1, arr, ARR_SIZE, sizeof(arr[0]), compare);
	if (p1)
		std::cout << "value " << key1 << " found at position " << (p1 - arr) << '\n';
	else
		std::cout << "value " << key1 << " not found\n";

	int key2 = 9;
	int *p2 = (int *)std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare);
	if (p2)
		std::cout << "value " << key2 << " found at position " << (p2 - arr) << '\n';
	else
		std::cout << "value " << key2 << " not found\n";

	system("pause");
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值