www.delorie.com/djgpp/doc/libc-2.01/libc_72.html   search  
Go to the first, previous, next, last section, table of contents.


bsearch

Syntax

#include <stdlib.h>

void *bsearch (const void *key, const void *base, size_t num, 
  size_t size, int (*ptf)(const void *ckey, const void *celem));

Description

Given an array of values, perform a binary search on the values looking for value that "matches" the given key. A match is determined by calling the provided function ptf and passing it the key as ckey and a pointer to one of the elements of the array as celem. This function must return a negative number if the key is closer than the element to the beginning of the array, positive if it is closer to the end, and zero if the element matches the key.

The array begins at address base and contains num elements, each of size size.

Return Value

Returns a pointer to the element that matches the key, else NULL.

Example

typedef struct {
  int a, b;
} q;

int compare(void *key, void *elem)
{
  return *(int *)key - ((q *)elem)->a;
}

q qlist[100];

...
q *match = bsearch(4, qlist, 100, sizeof(q), compare);
printf("4->%d=n", match->b);
...


Go to the first, previous, next, last section, table of contents.

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright © 1997   by DJ Delorie     Updated Apr 1997  

Please take a moment to fill out this visitor survey
You can help support this site by visiting the advertisers that sponsor it! (only once each, though)