1 /* $NetBSD: tsearch.c,v 1.4 1999/09/20 04:39:43 lukem Exp $ */
4 * Tree search generalized from Knuth (6.2.2) Algorithm T just like
5 * the AT&T man page says.
7 * The node_t structure is for internal use only, lint doesn't grok it.
9 * Written by reading the System V Interface Definition, not the code.
11 * Totally public domain.
15 #define _SEARCH_PRIVATE
16 #include <tsearch/search.h>
20 /* find or insert datum into search tree */
22 tsearch(const void * __restrict__ vkey
, /* key to be located */
23 void ** __restrict__ vrootp
, /* address of tree root */
24 int (*compar
) (const void *, const void *))
27 node_t
**rootp
= (node_t
**)vrootp
;
32 while (*rootp
!= NULL
) { /* Knuth's T1: */
35 if ((r
= (*compar
)(vkey
, (*rootp
)->key
)) == 0) /* T2: */
36 return *rootp
; /* we found it! */
39 &(*rootp
)->llink
: /* T3: follow left branch */
40 &(*rootp
)->rlink
; /* T4: follow right branch */
43 q
= malloc(sizeof(node_t
)); /* T5: key not found */
44 if (q
!= 0) { /* make new node */
45 *rootp
= q
; /* link new node to old */
46 /* LINTED const castaway ok */
47 q
->key
= (void *)vkey
; /* initialize new node */
48 q
->llink
= q
->rlink
= NULL
;