二分查找在字符串中的应用范例

typedef struct _Nameval {
char *name;
int value;
} Nameval;

Nameval htmlchars[] = {
"AElig", 0x00c6,
"Aacute", 0x00c1,
/* ... */
"zera", 0x03b6,
};

int lookpu(char *name, Nameval tab[], int ntab)
{
    int low, high, mid, cmp;
    low = 0;
    high = ntab - 1;
    while (low <= high) {
        mid = (low + high) / 2;
        cmp = strcmp(name, tab[mid].name);
        if (cmp < 0)
        high = mid - 1;
        else if (cmp > 0)
        low = mid + 1;
        else
            return mid;
    }
    return -1;
}
posted @ 2014-03-22 17:32  thinker-lj  Views(230)  Comments(0Edit  收藏  举报