[comp.lang.c] bsearch implementation help

t-lee@sylvester.columbia.edu (Tim Lee) (01/15/87)

I'm attempting to write the equivalent of the bsearch function call
that is available in UNIX SYSV.  The problem that I am having is that
I don't know how to pass two array elements to the compare function
that the user supplies.  I can determine the address of any element in
the array, but do not know how to use the key as an array element...

The specifications for this routine should read exactly like the MAN
page for the bsearch function in UNIX.  Does anybody out there have a
clue as to how I should go about doing this?

Please try to send replies to: 

(internet)  x1.micky@cu20b.columbia.edu
  (usenet)  ...seismo!columbia!cu20b!x1.micky
                              !kirkwood!m-liu



Here is the unfinished routine:
----------------------------------------------------------------------

#include <stdio.h>


char *bsearch(key,base,num,width,compare)

char *key;
char *base;
unsigned num;
unsigned width;
int  (*compare)();


{
int  cond;
char *mid;

int  llo = 0;
int  hhi = num - 1;
int  mmi;

     while (llo <= hhi)
     {
          mmi = (llo + hhi) /2;
          mid = base + (width * mmi);
          if ((cond = (*compare)(key,mid)) < 0)
               hhi = mmi - 1;
          else if (cond > 0)
               llo = mmi + 1;
          else
               return(mid);
     }
     return((char *)NULL);
}