之前查看qsort函数的时候无意间看到了一个C语言内置的查找函数bsearch.
#include <stdlib.h>
void *bsearch( const void *key, const void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );
功能:函数用折半查找法在从数组元素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;
}