This is the mail archive of the newlib@sourceware.org mailing list for the newlib project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

No bsearch and qsort?


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]