summaryrefslogtreecommitdiff
path: root/libc/stdlib/bsearch.c
blob: 72ba2617a1d73d8455f074f2c63bf7d3cd43094c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

/*
 * This file lifted in toto from 'Dlibs' on the atari ST  (RdeBath)
 *
 * 
 *    Dale Schumacher                         399 Beacon Ave.
 *    (alias: Dalnefre')                      St. Paul, MN  55104
 *    dal@syntel.UUCP                         United States of America
 *  "It's not reality that's important, but how you perceive things."
 */
#include <stdio.h>

static int _bsearch;		/* index of element found, or where to
				 * insert */

char *
bsearch(key, base, num, size, cmp)
register char *key;		/* item to search for */
register char *base;		/* base address */
int   num;			/* number of elements */
register int size;		/* element size in bytes */
register int (*cmp) ();		/* comparison function */
{
   register int a, b, c, dir;

   a = 0;
   b = num - 1;
   while (a <= b)
   {
      c = (a + b) >> 1;		/* == ((a + b) / 2) */
      if ((dir = (*cmp) ((base + (c * size)), key)))
      {
	 if (dir > 0)
	    b = c - 1;
	 else			/* (dir < 0) */
	    a = c + 1;
      }
      else
      {
	 _bsearch = c;
	 return (base + (c * size));
      }
   }
   _bsearch = b;
   return (NULL);
}