C library function -bsearch()

C Standard Library - <stdlib.h>

bsearch is a function in the C standard library, used to perform a binary search in a sorted array. Its definition is in the stdlib.h header file.

C Library Functionsvoid *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))PairnitemsPerform a binary search on an array of objects,basePoints to the array being searched,keyPoints to the element to be searched for,sizeSpecifies the size of each element in the array.

The contents of the array should be sorted in ascending order according tocomparthe corresponding comparison function.

Declaration

The following is the declaration of the bsearch() function.

void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

Parameter

  • key: Pointer to the target element to be searched for.
  • base: Pointer to the starting position of the array.
  • nmemb: Number of elements in the array.
  • size: The size of each element (in bytes).
  • compar: Pointer to the comparison function, which is used to compare two elements.

Return Value

  • If a matching element is found,bsearchreturn a pointer to that element.
  • If no matching element is found,bsearchreturnNULL。

Comparison function

The comparison function must match the following signature:

int compar(const void *a, const void *b);

Function returns:

  • A negative value, ifaless thanb。
  • Zero, ifaequalsb。
  • A positive value, ifagreater thanb。

Example

The following example demonstrates the usage of the bsearch() function.

Example

#include <stdio.h> #include <stdlib.h> // Comparison function, used for bsearch lookup int cmpfunc(const void * a, const void * b) { return (*(int*)a - *(int*)b); } int main() { int values[] = { 5, 20, 29, 32, 63 }; int key = 32; int *item; // Calculate the array length size_t array_size = sizeof(values) / sizeof(values[0]); // Use bsearch to find value 32 in the array item = (int*) bsearch(&key, values, array_size, sizeof(int), cmpfunc); // Check the search result and output it if (item != NULL) { printf("Found item = %d\n", *item); } else { printf("Item = %d could not be found\n", key); } return 0; }

Let us compile and run the above program, which will produce the following result:

Found item = 32

C Standard Library - <stdlib.h>

other extensions