1

how can you sort char firstName in a function and the names are read in from a text file already and 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];
}
2
  • You can format code by selecting it and pressing CTRL+K. Use the preview. Commented Nov 24, 2010 at 22:10
  • Also, your question doesn't provide nearly enough information. What kind of array/collection do you have? This struct doesn't tell us anything. Commented Nov 24, 2010 at 22:10

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

In reference to the qsort(3) man page, you'll see that StudentCompare() is the 'compar' argument. If you have struct student students[100];, then you would call qsort(students, 100, sizeof(struct student), StudentCompare);
Also, I think it should be 'struct student' instead of just 'student' in the StudentCompare() implementation.
@Wade, thanks for that. I've been spoiled by C++ for far too long. Edited.
0

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.

1 Comment

Insertion sort is typically a touch simpler and a touch faster. Also, qsort() is not an external library, but is included in the C standard library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.