问题
Is there a built in function in C for searching an integer array that has been sorted?
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.
回答1:
stdlib.h
actually contains some sorting and searching functions. qsort
will let you sort an array in place, and bsearch
will perform binary search on a sorted array for you. You do have to provide a comparison function in both cases.
回答2:
There is bsearch()
for binary search in sorted array https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm
Example:
#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 Added proper comparer by @jonathan-leffler
回答3:
you need bsearch, this link will take you to the manual and an example provided in that manual. alternatively in a linux box you can type
man -a bsearch
来源:https://stackoverflow.com/questions/47320667/built-in-function-for-searching-sorted-array-in-c