Data Management: Sorts, Lists, and Indexes |
C C C |
|
10C |
|
C C C |
|
C C |
qsort((void *)pBuffer, (size_t)nLine, sizeof(char *), compare);
When qsort() returns, the program uses printf() to write the final sorted output:
fprintf(stderr, “Writing output...\n”);
for (i = 0; i < nLine; i++)
{
printf(“%s\n”, pBuffer[i]);
}
Because the printf() output goes to stdout, the output could be redirected to a file. Finally, the blocks of memory are freed and the program ends:
for (i = 0; i < nCurrentBlock; i++)
{
free(pBlocks[i]);
}
The compare function, which is called by qsort() in the main program, is simple. The program calls strcmp(). If you want the program to ignore case, you could call stricmp() instead. You could also create your own function to compare the strings, but C’s functions work well enough.
int compare( char **arg1, char **arg2)
{
return strcmp(*arg1, *arg2);
}
The SORTFILE program can sort files up to 500K, depending on the DOS version). You could use SORTFILE also with I/O redirection or as a filter with DOS’s pipe operator, |.
Merging
No matter how much memory you have available, eventually you will want to sort a file that is too large. You could sort the file from the disk. Another method is to break