C 中是否有内置函数用于搜索已排序的整数数组?
我可以轻松实现它,但这似乎是一件很常见的事情 - 如果没有库/内置 C 函数,那会很奇怪。
stdlib.h
实际上包含一些排序和搜索函数。 qsort
将允许您就地对数组进行排序,bsearch
将为您对排序后的数组执行二叉搜索。在这两种情况下,您都必须提供比较功能。
排序数组 https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm 中存在二叉搜索bsearch()
例:
#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 = %dn", *item);
} else {
printf("Item = %d could not be foundn", *item);
}
return(0);
}
UPD通过@jonathan-莱夫勒添加了适当的比较器
您需要 bsearch,此链接将带您进入手册和该手册中提供的示例。 或者,在 Linux 框中,您可以键入
man -a bsearch