内置函数,用于在C中搜索排序数组 [英] Built in function for searching sorted array in C
本文介绍了内置函数,用于在C中搜索排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C中是否有内置函数来搜索已排序的整数数组?
Is there a built in function in C for searching an integer array that has been sorted?
我可以很容易地实现它,但是这看起来很普通-如果没有库或内置的C函数会很奇怪.
I can easily implement it but it seems like such a common thing - would be weird if there is no library/built in C function.
推荐答案
There is bsearch()
for binary search in sorted array https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm
示例:
#include <stdio.h>
#include <stdlib.h>
int cmp_int(const void *pa, const void *pb) {
int a = *(int *)pa;
int b = *(int *)pb;
return (a > b) - (a < b);
}
int values[] = { 5, 20, 29, 32, 63 };
int main () {
int *item;
int key = 32;
/* using bsearch() to find value 32 in the array */
item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
if( item != NULL ) {
printf("Found item = %d\n", *item);
} else {
printf("Item = %d could not be found\n", *item);
}
return(0);
}
UPD 通过@ jonathan-leffler添加了适当的比较器
UPD Added proper comparer by @jonathan-leffler
这篇关于内置函数,用于在C中搜索排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文