Compiled using VC6.0
The program uses top-down procedural programming and uses dynamic arrays to store words. Strings are read from files one by one, and they are also judged to see if they are letters, '-', or ,'-','''; if yes, it is stored in the string. If no, the end character of the string is added and the entire string is processed. For string search and insertion, the binary search and sequential insertion algorithms are used. Finally, a maximum of 15 sorting algorithms are selected and output to the file.
// The following is the program code.
# Include "stdio. h"
# Include "stdlib. h"
# Include "string. h"
# Include "ctype. h"
Typedef struct // store a word and its number
{
Char str [25];
Int num;
} Str;
Str * word;
Int Look (Str word1, int n) // use the Binary Search Method
{
Int start = 1, end = n-1, mid;
If (n = 1) return 1;
While (start <= end)
{
Mid = (start + end)/2;
If (strcmp (word1.str, word [mid]. str) = 0)
{
Word [Mid]. Num ++;
Return 0;
}
If (strcmp (word1.str, word [Mid]. Str)> 0)
End = mid-1;
Else start = Mid + 1;
}
Return 1;
}
Int hsort (STR word1, int N) // sort Inserts
{
If (n = 1)
{
Strcpy (word [1]. STR, word1.str );
Word [1]. num = word1.num;
Return 0;
}
Int I;
For (I = n-1; I >=1 & strcmp (word1.str, word [I]. Str)> = 0; I --) // move the array backwards
{
Strcpy (word [I + 1]. STR, word [I]. Str );
Word [I + 1]. num = word [I]. num;
}
Strcpy (word [I + 1]. str, word1.str); // insert
Word [I + 1]. num = word1.num;
Return I + 1;
}
Void Isort (int n) // use the sorting method to find up to 15
{
Int I, j, max;
Str ss;
For (I = 1; I <17; I ++) // find the 16 largest
{
Max = I; // find the largest I
For (j = I + 1; j <= n; j ++)
If (word [j]. num> word [max]. num) max = j;
Ss = word [max]; // exchange
Word [max] = word [I];
Word [I] = ss;
}
}
Void main ()
{
FILE * fin;
Char c;
Str word1;
Int strlen, Maxlen, count, I;
Maxlen = 50;
Strlen = 0;
Count = 1;
Fin = fopen ("c: \ a.txt", "r"); // open the document for statistics, for example, a.txt under drive c.
Word = (Str *) malloc (sizeof (Str) * (50); // initially allocate 50 Str Spaces
While (c = fgetc (fin ))! = EOF)
{
If (isalpha (c) | c = '\ ''| c ='-') word1.str [strlen ++] = c;
While (c = fgetc (fin ))! = EOF & (isalpha (c) | c = '\ ''| c = '-'))
Word1.str [strlen ++] = c;
Word1.str [strlen] = '\ 0 ';
Word1.num = 1;
If (count> = maxlen) // check whether the space is sufficient. If not, add
{
WORD = (Str *) realloc (word, maxlen + 10 );
Maxlen + = 10;
}
If (look (word1, count) & strlen> 0) // process the string
{
Int T;
T = hsort (word1, count );
Count ++;
}
Strlen = 0;
}
Fclose (FIN );
Isort (count); // sorts strings
Fin = fopen ("C: \ B .txt", "W"); // you can change the path to open the output file, but note '\'
Fprintf (FIN, "the top 15th words: \ n ");
For (I = 1; I <16; I ++) // output the 15 largest
Fprintf (FIN, "%-20 S % d \ n", word [I]. STR, word [I]. Num );
System ("pause ");
}
Http://tanyufeng521.weebly.com/1/post/2012/03/4.html