ack/lang/cem/libcc.ansi/core/stdlib/bsearch.c

31 lines
695 B
C
Raw Permalink Normal View History

1989-05-16 13:13:53 +00:00
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
1994-06-24 14:02:31 +00:00
/* $Id$ */
1989-05-16 13:13:53 +00:00
2018-06-21 20:33:47 +00:00
#include <stdlib.h>
1989-05-16 13:13:53 +00:00
2018-06-21 20:33:47 +00:00
void* bsearch(register const void* key, register const void* base,
register size_t nmemb, register size_t size,
int (*compar)(const void*, const void*))
1989-05-16 13:13:53 +00:00
{
2018-06-21 20:33:47 +00:00
register const void* mid_point;
register int cmp;
1989-05-16 13:13:53 +00:00
2018-06-21 20:33:47 +00:00
while (nmemb > 0)
{
mid_point = (char*)base + size * (nmemb >> 1);
1989-05-16 13:13:53 +00:00
if ((cmp = (*compar)(key, mid_point)) == 0)
2018-06-21 20:33:47 +00:00
return (void*)mid_point;
if (cmp >= 0)
{
base = (char*)mid_point + size;
1989-05-16 13:13:53 +00:00
nmemb = (nmemb - 1) >> 1;
2018-06-21 20:33:47 +00:00
}
else
1989-05-16 13:13:53 +00:00
nmemb >>= 1;
}
2018-06-21 20:33:47 +00:00
return (void*)NULL;
1989-05-16 13:13:53 +00:00
}