The bsearch () can be used in the C language for binary search. As with Qsort (), bsearch () is also included in the library, and the comparison sub-function is also customized. The prototype is as follows:
void *bsearch (const void *key, const void *base, size_t nmem, size_t size, int (*comp) (const void *, const void *));
Header files: #include <stdlib.h>
Key points to the element you are looking for, base points to the array you are looking for, Nmem is a lookup length, typically an array length, size is the number of bytes per element, usually with sizeof (...). Representation, Comp points to the comparison sub-function, which defines the rules for comparison. It is important to note that the data must be pre-ordered, and the rules for sorting are the same as comp points to the comparison sub-function. If the lookup succeeds, the address of the matching element in the array is returned, and the inverse returns NULL. For cases where more than one element matches successfully, bsearch () does not define which one to return.
Cases:
#include <stdio.h>#include <stdlib.h> #define NUM 8int Compare (const void *p, const void *q) { Return (* (int *) P-* (int *) q);} int main (int argc, char *argv[]) { int array[num] = {9, 2, 7, one, 3,, 6}; int key = 3; int *p; qsort (array, num, sizeof (int), compare), p = (int *) bsearch (&key, array, num, sizeof (int), compare); (p = = NULL)? Puts ("Not found"): Puts ("found"); return 0;}
The results are as follows: Found
Find operation with bsearch () in C language