开发者

how To sort char name in a struct using C Language

how can you sort char firstName in a function and the names are read in from a text file already and开发者_C百科 external libraries can be used as well All students names are provided in a text file, which is read into an array of student records

struct student{
   char*lastName; /*name of the student*/
   char*firstName;
   int age;       /*age of the student*/
   float grade[3];
}


The qsort function is typically used in C to sort an array. One of the parameters is a pointer to a comparison function. Write the function so that it compares the two pointers in any fashion you want. You can even have different comparison functions so that you have the choice at run-time which will be applied.

int StudentCompare(const void * elem1, const void * elem2)
{
    const struct student * left = (const struct student *) elem1;
    const struct student * right = (const struct student *) elem2;
    int result;
    result = strcmp(left.firstName, right.firstName);
    if (result == 0)
        result = strcmp(left.lastName, right.lastName);
    return result;
}


The easy way, assuming you're not allowed to use external libraries, is with bubblesort. Write a function that determines if an array of struct students is already sorted. Then write a function that walk through such an array, comparing adjacent pairs of students. If they're out of order, swap them. Use the first function's result as the conditional clause of a while loop and the second function as the body.

If you are allowed to use it, then qsort() from stdlib.h is by far the best approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜