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 - 如何使用 getifaddr() 函数获取 IPV6 接口(interface)地址

c - 为c中的一组趋势线分配不同的权重

Java二进制搜索递归

python - 查找数组中的最大元素,先升序再降序排序

search - 推力矢量化搜索 : Efficiently combine lower_bound and binary_search to find both position and existence

python - 这个程序如何运作? firstGreaterEqual 方法如何工作

c - 如何使用 "\a"转义字符发出蜂鸣声?

c - 这些系统调用有什么问题?

c++ - 无法正确实现upper_bound()

c - C语言中如何确定文件的大小?