CodeCogs
HomeForumsCart
Login



Forgotten Password?

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
ComputingCStdlib.h

bsearch

Binary search of a sorted table

Interface

#include <stdlib.h>
void bsearch (const void *key, const void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))

Description

The bsearch function searches an array of \c nmemb objects, the initial member of which is pointed to by \c base, for a member that matches the object pointed to by \c key. The size of each member of the array is specified by \c size.

The contents of the array should be in ascending sorted order according to the comparison function referenced by \c compar. The \c compar routine is expected to have two arguments which point to the \c key object and to an array member, in that order, and should return an integer less than, equal to, or greater than zero if the \c key object is found, respectively, to be less than, to match, or be greater than the array member.

The code below searches for the string "strawberries" in an array of strings, which initially is not sorted. Therefore, reference:qsort is used to sort the array first and then bsearch is used.

Example 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char strings[][20] = {"apples", "grapes", "strawberries", "bananas"};
 
int main ()
{
  char item[20] = "strawberries";
 
  // first make sure the strings are sorted
  qsort(strings, 4, 20, (int(*)(const void*, const void*))strcmp);
 
  // search for "strawberries"
  char *pos = (char*) bsearch(item, strings, 4, 20, (int(*)(const void*, const void*))strcmp);
 
  if (pos)
    printf("The string "%s" has been found.\n", pos);
  else
    printf("The string "%s" has not been found.\n", item);
 
  return 0;
}

Output:
The string "strawberries" has been found.

Return Values

The bsearch function returns a pointer to a matching member of the array, or a null pointer if no match is found. If two members compare as equal, which member is matched is unspecified.

Last Modified: 18 Dec 11 @ 14:14     Page Rendered: 2022-03-14 15:48:19