illustration of qsort using Microsoft Visual C++
/* illustration of the C library function qsort();
qsort() is a very efficient implementation of the Quicksort
(actually Quickersort) algorithm;
the C library function allows sorting of nonnumerical objects,
so the user must supply his/her own comparison function, which
defines whether one object is "smaller" than another;
in our example here, an "object" will be a character string;
one string is considered "less than" an other if the first
string would come before the second if they were listed in a
dictionary (so this is called "lexicographic ordering," from
the word "lexicon," which means "dictionary")
this comparison can be done by the C library function strcmp(),
but here we wish to make no distinction between lower- and
upper-case letters, so we cannot use strcmp(); thus we are
providing our own function instead, MyStrcmp()
the compare-function has two arguments, which are the addresses
of the two items to be compared, and returns an integer value
which is either less than 0 (signifying that the first object
is "less than" the second), equal to 0 (signifying that the
two objects are equal) or greater than 0 (signifying that the
first object is greater than the second */
#include <stdafx.h>
#include <string.h>
#include <stdlib.h>
#define MaxNWords 100
#define MaxWordLength 20
char Word[MaxNWords][MaxWordLength]; /* array of words to be sorted */
int MyOwnStrcmp(char *WordPtrA, char *WordPtrB)
{ char LCWord[2][MaxWordLength],C;
int UpperVsLowerDiff,I,J;
/* first, make copies of the two input strings, except that in
the copies all upper-case letters have been changed to lower-
case */
strcpy(LCWord[0],WordPtrA);
strcpy(LCWord[1],WordPtrB);
UpperVsLowerDiff = 'a' - 'A';
for (I = 0; I < 2; I++)
for (J = 0; J < MaxWordLength; J++) {
C = LCWord[I][J];
if (C >= 'A' && C <= 'Z')
LCWord[I][J] += UpperVsLowerDiff;
}
/* OK, now we can use the ordinary strcmp() function */
return strcmp(LCWord[0],LCWord[1]);
}
void main()
{ int I,NWords;
printf("enter words, with ctrl-d to end\n");
for (NWords = 0; ; NWords++) {
scanf("%s",Word[NWords]);
if (strcmp(Word[NWords],"mike") == 0) break;
}
/* qsort()'s parameters are:
address of the first object
number of objects
sizeof(object)
name of the compare-function */
//qsort(Word,NWords,MaxWordLength, ((int *)()) &MyOwnStrcmp);
///typedef (int *ccc)(void *, void *);
// typedef int (*c)(void *, void *);
qsort(Word,NWords,MaxWordLength, (int ( * )(const void *, const void *)) MyOwnStrcmp);
// qsort(
printf("\n\nsorted array:\n");
for (I = 0; I < NWords; I++) printf("%s\n",Word[I]);
fflush(stdin);
getchar();
}
0 Comments:
Post a Comment
<< Home