No bsearch and qsort?

Gregory Pietsch gpietsch@comcast.net
Sat Feb 14 00:52:00 GMT 2009


I noticed that there wasn't a bsearch or a qsort in stdlib. Both of 
these should be fairly easy to write. There's a bsearch in libiberty but 
no qsort.

Here's a quick stab at bsearch:

/* bsearch function */

#include <stdlib.h>

void *(bsearch)(const void *key, const void *base, size_t nelem, size_t 
size, int (*compar)(const void *, const void *))
{
  const char *pbase = (const char *) base, *q;
  size_t lo, hi, g;
  int c;

  for (lo = 0, hi = nelem - 1; lo <= hi; )
    {
      /* make a new guess */
      g = (lo + hi) >> 1;
      q = pbase + (g * size);
      c = (*compar)(key, (const void *)q);
      if (c == 0)
        return (const void *)q;   /* found it */
      else if (c < 0)
        {
          if (g == 0)
            return 0;    /* no match */
          hi = g - 1;
        }
      else
        lo = g + 1;
    }
  return 0;   /* no match */
}

/* END OF FILE */

I've seen several implementations of qsort that are as trivial. I could 
post one that works easily.

So, why aren't these functions in stdlib?

Gregory



More information about the Newlib mailing list