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 
#include 
#include 

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;
}

 

你可能感兴趣的:(c++,c++)