問題
編寫 一個程序,統計輸入中C語言每個關鍵字的出現次數。
算法分析
While ( 仍有新單詞讀入)
If(新單詞是否是關鍵字)
相應關鍵字出現次數加1;
輸出關鍵字及出現次數;
定義一個結構用以表示關鍵字與其出現次數:
struct Key {
char *keyword;
int count;
};
關鍵字表的組織:使用一個有序(提高效率)的結構數組來存放關鍵字表及關鍵字出現次數:
struct Key Keytab[ ] = {
"auto", 0,
"break",0,
"case", 0,
...
"while", 0
};
在有序數據集中查找指定數據項最常用及最快的算法是折半查找算法
算法實現
#include <stdio.h>
struct Key {
char *keyword;
int keycount;
} Keytab[ ] = {
"auto", 0,
"break", 0,
"case", 0,
...
"while", 0
};
#define MAXWORD 20
#define NKEYS (sizeof(Keytab) / sizeof(struct Key))
#define LETTER 'a'
#define DIGIT '0'
struct Key *binary(char *word, struct Key tab[ ], int n);
char getword(char *w, int lim);
char type( int c);
void printKey(struct Key tab[ ], int n);
int main( ) /* count C keyword */
{
int t;
char word[MAXWORD];
struct Key *p;
while((t = getword(word, MAXWORD)) != EOF)
if( t = = LETTER)
if(( p = binary(word, Keytab, NKEYS)) != NULL)
p->keycount++;
printKey(keytab, NKEYS);
return 0;
}
struct Key *binary(char *word, struct Key tab[ ], int n)
{
int cond;
struct Key *low = &tab[0];
struct Key *high = &tab[n-1];
struct Key *mid;
while(low <= high){
mid = low + (high – low) / 2;
if((cond = strcmp(word, mid->keyword)) < 0)
high = mid – 1;
else if ( cond > 0)
low = mid + 1;
else
return (mid);
}
return (NULL);
}
char getword(char *w, int lim)
{
int c, t;
if(type(c = *w++ = getchar( )) != LETTER){
*w = '\0';
return ( c);
}
while(--lim > 0) {
t = type(c = *w++ = getchar( ));
if( t != LETTER && t != DIGIT){
ungetc(c,stdin);
break;
}
}
*(w-1) = '\0';
return ( LETTER);
}
char type(int c) /* return type of ASCII character */
{
if( c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
return ( LETTER );
else if ( c >= '0' && c <= '9')
return ( DIGIT );
else return (c);
}
void printKey(struct Key tab[ ], int n)
{
struct Key *p;
for(p=Keytab, p < Keytab+n; p++)
if(p->keycount > 0)
printf("%4d%s\n", p->keycount, p->keyword);
}