Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
struct key {
char *word;
int count;
} keytab[] = {
"int", 0,
"for", 0,
"break", 0,
"case", 0,
"char", 0,
"const", 0,
"continue", 0,
"default", 0,
"unsigned", 0,
"void", 0,
"volatile", 0,
"while", 0
};
#define NKEYS (sizeof keytab / sizeof(struct key))
int binsearch(char *, struct key *, int);
int search(char *word, struct key tab[], int n);
/* count C keywords */
int main(void)
{
struct key *p = keytab;
char *word = "ddog";
int n;
//n = search(word, p, NKEYS);
n = binsearch(word, p, NKEYS);
printf("n=%d\n", n);
return 0;
}
/* binsearch: find word in tab[0]...tab[n-1] */
int binsearch(char *word, struct key tab[], int n)
{
int cond;
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low+high) / 2;
cond = strcmp(word, tab[mid].word); printf("cond=%d\n", cond);
if (cond < 0)
high = mid - 1;
else if (cond > 0)
low = mid + 1;
else
return mid;
}
return -1;
}
int search(char *word, struct key tab[], int n)
{
for ( n-=1; n >= 0; n--) {
if (!strcmp(word, tab[n].word))
return n;
}
return -1;
}