用C语言实现一个非递归的二分查找算法其实并不算太难,但要求对各种数据类型通用,其难度就有些增加了。
C语言没有函数模版,所以主要使用了void指针和函数指针。
具体的代码如下:
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, UINT32 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;
}