c语言二分查找泛型实现

来源:互联网 发布:微信开发入门教程 php 编辑:程序博客网 时间:2024/05/22 17:19
int intCmp(const void *lhs, const void *rhs){    int a = *(int*)lhs;    int b = *(int*)rhs;    if (a > b)        return 1;else if (a == b)        return 0;else        return -1;}int bSearch(void *array, const void *elem, const int elemSize, const int arraySize, int (*cmp)(const void *lhs, const void *rhs)){    int left = 0;    int right = arraySize - 1;    while (left <= right)    {        int mid = (left + right)/2;        char *tmp = (char *)array;        int result = cmp(elem, tmp+mid*elemSize);        if (result == 0)            return mid;else if (result > 0)            left = mid + 1;else            right = mid - 1;    }    return -1;}


实现中cmp回调实现是需要知道泛型的实际类型,可以用memcmp替换该函数。

0 0