Using C language to implement a non-recursive binary lookup algorithm is not too difficult, but the requirements for a variety of data types general, the difficulty is somewhat increased.
C language has no function template, so the main use of void pointers and function pointers.
The specific code is as follows:
typedef int (*cmp_fun) (const void *key, const void *DST);
#define GET_DATA (arr, POS, size) (UINT8 *) (arr) + (POS) * (size)
void *bisearch (CONST void *ptable, UINT32 Cnt, UINT Size, VOID *key, Cmp_fun cmpfunc)
{
INT32 Start, Mid, end;
Start = 0;
end = Cnt-1;
if (Start > End) {return
NULL;
}
While [start <= end] {
Mid = (start + end)/2;
if (Cmpfunc (Key, Get_data (ptable, Mid, Size) < 0) {end
= Mid-1;
}
else if (Cmpfunc Key, Get_data (ptable, Mid, Size) > 0) {
Start = Mid + 1;
}
else {return
get_data (ptable, Mid, Size);
}
}
return NULL;
}