CircAnalyzer
CircAnalyzer

Reputation: 704

Sort Struct records

I have a structure that contains a field for student names. I'd like to order the names alphabetically. Here is the list of names that are stored into the name field of the structure:

Thui Bhu
Ariana B. Smith
Emily Gonzales
Jennifer L
Maria Jones
Bill Gates
Escobar Morris
Anne Latner

Here is the way I am defining the structure:

struct studentData {
        char name[30];
        int quiz1; int quiz2;
        int quiz3; int quiz4;
        int mid1; int mid2;
        int finalexam;
    } ;

Here is the code I have tried using to sort:

void SortNames(struct studentData *record, int reccount)
{
    int j,i;
    struct studentData temp;
    for(i = 1; i < reccount; i++)
    {
        j = i - 1;
        while( j >= 0 && strcmp( record[j+1].name, record[j].name) < 0 )
        {
            temp =  record[j + 1]; /*errors*/
            record[j+1] = record[j];
            record[j] = temp; /*errors*/
            j--;
        }
        printf("%s",record[j].name);
    }
   return;
}

This is the output that I am getting:

Ariana B. SmithEmily GonzalesJennifer LAriana B. SmithEmily Gonzales

Please help! I am open to using any built-in functions.

Upvotes: 0

Views: 81

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84599

Unless you need to create your own sort routine, the best approach is probably using the qsort function to sort the structs by name. When using qsort your task is simply to create a comparator funciton that takes a void pointer to type struct studentData and creates a way to compare by the member of interest (here name)

The qsort comparison funciton returns type int. For your struct it would look something like:

/* qsort struct comparision function (struct studentData by name) */
int struct_cmp_by_name (const void *a, const void *b)
{
    struct studentData *ia = (struct studentData *)a;
    struct studentData *ib = (struct studentData *)b;
    return strcmp (ia->name, ib->name);
}

(Note - you don't have qutie enough code posted to be exact, but it will be close to being) called in your code as:

qsort (record, number_structs, sizeof (struct studentData), struct_cmp_by_name);

This will sort records by the member name.

Upvotes: 1

timrau
timrau

Reputation: 23058

Call qsort().

#include <stdlib.h>
#include <string.h>
int cmp(const void *l, const void *r)
{
    return strcmp(((struct studentData*)l)->name, ((struct studentData*)r)->name);
}

void SortNames(struct studentData *record, int reccount)
{
    int i;
    qsort(record, reccount, sizeof(struct studentData), cmp);
    for (i = 0; i < reccount; ++i) {
        printf("%s\n", record[i].name);
    }
}

Upvotes: 2

Related Questions