我正在写一个键记录查找我在键和记录号之间有一个索引的位置。这是按键排序的。有没有比我在速度优化方面做得更好的方法?
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;
}