Home | History | Annotate | Line # | Download | only in stdlib
      1  1.7       abs /*	$NetBSD: tfind.c,v 1.7 2012/06/25 22:32:45 abs Exp $	*/
      2  1.1  christos 
      3  1.1  christos /*
      4  1.1  christos  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
      5  1.1  christos  * the AT&T man page says.
      6  1.1  christos  *
      7  1.1  christos  * The node_t structure is for internal use only, lint doesn't grok it.
      8  1.1  christos  *
      9  1.1  christos  * Written by reading the System V Interface Definition, not the code.
     10  1.1  christos  *
     11  1.1  christos  * Totally public domain.
     12  1.1  christos  */
     13  1.1  christos 
     14  1.1  christos #include <sys/cdefs.h>
     15  1.1  christos #if defined(LIBC_SCCS) && !defined(lint)
     16  1.7       abs __RCSID("$NetBSD: tfind.c,v 1.7 2012/06/25 22:32:45 abs Exp $");
     17  1.1  christos #endif /* LIBC_SCCS and not lint */
     18  1.1  christos 
     19  1.2     lukem #include <assert.h>
     20  1.1  christos #define _SEARCH_PRIVATE
     21  1.1  christos #include <stdlib.h>
     22  1.1  christos #include <search.h>
     23  1.1  christos 
     24  1.7       abs /* find a node by key "vkey" in tree "vrootp", or return 0 */
     25  1.1  christos void *
     26  1.7       abs tfind(const void *vkey, void * const *vrootp,
     27  1.7       abs     int (*compar)(const void *, const void *))
     28  1.1  christos {
     29  1.5    kleink 	node_t * const *rootp = (node_t * const*)vrootp;
     30  1.2     lukem 
     31  1.2     lukem 	_DIAGASSERT(vkey != NULL);
     32  1.2     lukem 	_DIAGASSERT(compar != NULL);
     33  1.1  christos 
     34  1.1  christos 	if (rootp == NULL)
     35  1.1  christos 		return NULL;
     36  1.1  christos 
     37  1.1  christos 	while (*rootp != NULL) {		/* T1: */
     38  1.1  christos 		int r;
     39  1.1  christos 
     40  1.1  christos 		if ((r = (*compar)(vkey, (*rootp)->key)) == 0)	/* T2: */
     41  1.1  christos 			return *rootp;		/* key found */
     42  1.1  christos 		rootp = (r < 0) ?
     43  1.1  christos 		    &(*rootp)->llink :		/* T3: follow left branch */
     44  1.1  christos 		    &(*rootp)->rlink;		/* T4: follow right branch */
     45  1.1  christos 	}
     46  1.1  christos 	return NULL;
     47  1.1  christos }
     48