c - c中的二进制搜索优化?

标签 c binary-search

我正在编写一个 key 记录查找,其中我在 key 和记录编号之间有一个索引。这是按键排序的。有什么办法比我的速度优化做得更好吗?

typedef struct
{
    char key[MAX_KEYLEN];
    int  rec;
} KeyRecPair;

typedef struct
{
    KeyRecPair *map;
    int         numRecs;
} KeyRecMap;

int GetRecFromKey(char *key, KeyRecMap *theMap)
{
    int cmpValue, bottom = 0;
    int half = theMap->numRecs / 2;
    int top = theMap->numRecs - 1;

    while (bottom != top)
    {
        cmpValue = strncmp(key, theMap->map[half].key, MAX_KEY_LEN); 

        if (cmpValue > 0)
        {
            /*top stays*/
            bottom = half + 1;
            half  = bottom + (top - bottom) / 2;
            continue;
        }
        if (cmpValue < 0)
        {
            /*bottom stays*/
            top = half - 1;
            half  = bottom + (top - bottom) / 2;
            continue;
        }
        return theMap->map[half].rec;
    }

    if (0 == strncmp(key, theMap->map[half].key, MAX_KEY_LEN))
        return theMap->map[half].rec;
    return 0;
}

最佳答案

您的大部分时间将花在 strncmp 上。

我建议将其设为 inlined ,或内联重写它,以避免头顶的函数调用。

如果您有勇气,可以unroll the loop一次或两次并看到性能提升。

如果您的字符串实际上是一个固定长度的 char 数组,您可以将长度设为 4 的倍数,然后使用 unsigned int 比较一次比较 4 个字节,而不是一次比较 1 个字节。

如果您没有 profiler , 你应该得到一个。剖析器可以轻松查看各种实现的相对成本。

另一种选择是选择一种不同的方式来组织您的数据。查看AVL trees寻找灵感。选择某种 Hashing功能,就像提到的其他功能一样,可能是一个可行的选择

关于c - c中的二进制搜索优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356928/

相关文章:

C:两种不同的二分搜索实现,一种陷入死循环

algorithm - 二分查找相关的编程难题

r - 如何加入具有多列和多个值的 data.table

字符串匹配的 C 代码 [Head First C] 似乎不起作用

c - 当我们从任何一个线程中出来时如何杀死剩余的线程?

c - 这将在 C 编程中做什么 :++group[ (int) (value[i]+0. 5)/10]

algorithm - 为什么二进制搜索索引以这种方式计算?

java - 为什么此二进制搜索代码在Eclipse IDE上给出错误的输出?

c# - 从 C++/Java/C# 代码调用 C 方法?

c - 为什么此C程序无法编译?