bsearch - C stdlib.h

C examples for stdlib.h:bsearch

Type

function

From


<cstdlib>
<stdlib.h>

Description

Binary search in array

Prototype

void* bsearch (const void* key,
               const void* base,
               size_t num,
               size_t size,
               int (*compare)(const void*,const void*));

Parameters

Parameter Description
key key Pointer .
base Pointer to the first object of the array.
num Number of elements in the array
size Size in bytes of each element in the array.
compare Pointer to a function that compares two elements.

Prototype of compare function:

int compare (const void* pkey, const void* pelem);

The function shall return:

return valuemeaning
<0pkey goes before pelem
0pkey is equivalent to the pelem
>0pkey goes after the pelem

A general compare function may look like:

int compareMyType (const void * a, const void * b)
{
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
}

Return Value

A pointer to an entry in the array that matches the search key.

If key is not found, a null pointer is returned.

Demo Code


#include <stdio.h>
#include <stdlib.h>

int compareints (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int values[] = { 5, 2, 6, 4, 1, 3 };

int main ()//w  ww  .  j  a v a 2 s . c om
{
  int * pItem;
  int key = 40;
  qsort (values, 6, sizeof (int), compareints);
  pItem = (int*) bsearch (&key, values, 6, sizeof (int), compareints);
  if (pItem!=NULL)
    printf ("%d is in the array.\n",*pItem);
  else
    printf ("%d is not in the array.\n",key);
  return 0;
}

bsearch example with strings

Demo Code


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char strvalues[][20] = {"x","a","0","p","some","example","strings","here","this"};

int main ()//from  ww w  .j a v  a  2 s .c o  m
{
  char * pItem;
  char key[20] = "example";

  /* sort elements in array: */
  qsort (strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp);

  /* search for the key: */
  pItem = (char*) bsearch (key, strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp);

  if (pItem!=NULL)
    printf ("%s is in the array.\n",pItem);
  else
    printf ("%s is not in the array.\n",key);
  return 0;
}

Related Tutorials