Files
glibc/stdlib/bsearch.c
T

50 lines
1.5 KiB
C
Raw Normal View History

/* Copyright (C) 1991,92,97,2000,02 Free Software Foundation, Inc.
1997-02-10 03:19:57 +00:00
This file is part of the GNU C Library.
1995-02-18 01:27:10 +00:00
1997-02-10 03:19:57 +00:00
The GNU C Library is free software; you can redistribute it and/or
2001-07-06 04:58:11 +00:00
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
1995-02-18 01:27:10 +00:00
1997-02-10 03:19:57 +00:00
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2001-07-06 04:58:11 +00:00
Lesser General Public License for more details.
1995-02-18 01:27:10 +00:00
2001-07-06 04:58:11 +00:00
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
1995-02-18 01:27:10 +00:00
#include <stdlib.h>
/* Perform a binary search for KEY in BASE which has NMEMB elements
of SIZE bytes each. The comparisons are done by (*COMPAR)(). */
1997-02-10 03:19:57 +00:00
void *
bsearch (const void *key, const void *base, size_t nmemb, size_t size,
2000-05-23 08:43:26 +00:00
int (*compar) (const void *, const void *))
1995-02-18 01:27:10 +00:00
{
1997-02-10 03:19:57 +00:00
size_t l, u, idx;
const void *p;
int comparison;
1995-02-18 01:27:10 +00:00
l = 0;
u = nmemb;
while (l < u)
{
idx = (l + u) / 2;
1997-02-10 03:19:57 +00:00
p = (void *) (((const char *) base) + (idx * size));
comparison = (*compar) (key, p);
1995-02-18 01:27:10 +00:00
if (comparison < 0)
u = idx;
else if (comparison > 0)
l = idx + 1;
else
1997-02-10 03:19:57 +00:00
return (void *) p;
1995-02-18 01:27:10 +00:00
}
return NULL;
}
libc_hidden_def (bsearch)