< c‎ | algorithm
Revision as of 01:04, 23 April 2013 by P12 (Talk | contribs)

Template:ddcl list begin <tr class="t-dsc-header">

Defined in header <stdlib.h>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td class="t-dcl-nopad">
void* bsearch( const void* key, const void* ptr, size_t count, size_t size,
               int (*comp)(const void*, const void*) );

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Finds an element equal to element pointed to by key in a sorted array pointed to by ptr. The array contains count elements of size bytes. The elements are compared using function pointed to by comp.

The behavior is undefined if the array is not already sorted in ascending order according to the same criteria that comp uses.

If the array contains several elements that comp would indicate as equal to the element searched for, then it is undefined which element the function will return as the result.



key - pointer to the element to search for
ptr - pointer to the array to examine
count - number of element in the array
size - size of each element in the array in bytes
comp - comparison function which returns ​a negative integer value if the first argument is less than the second,

a positive integer value if the first argument is greater than the second and zero if the arguments are equal. key is passed as the first argument, an element from the array as the second.
The signature of the comparison function should be equivalent to the following:

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

The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.

Return value

Pointer to the found element or NULL if such element has not been found.


#include <stdlib.h>
#include <stdio.h>
struct data {
  int nr;
  char const *value;
} dat[] = {
  {1, "Foo"}, {2, "Bar"}, {3, "Hello"}, {4, "World"}
int data_cmp(void const *lhs, void const *rhs) {
  struct data const *const l = lhs;
  struct data const *const r = rhs;
  return l->nr - r->nr;
int main(void) {
  struct data key = { .nr = 3 };
  struct data const *res = bsearch(&key, dat, sizeof(dat)/sizeof(dat[0]),
                                   sizeof(dat[0]), data_cmp);
  if(!res) {
    printf("No %d not found\n",;
  else {
    printf("No %d: %s\n", res->nr, res->value);


No 3: Hello

See also

Template:c/algorithm/dcl list qsort
C++ documentation for bsearch