GeekyCoder
GeekyCoder

Reputation: 67

C: how sort and subsort values in a structure

After hours of thinking and tinkering I almost gave up but decided to turn to the community for their help. I'm new to C and I just learned bubble sort. For example the following code sorts by name, what I would like to implement is a sub sort where it also sorts by person ID, how would I do that or change the following code to do just that? (This is structure problem).

struct human {
  char name;
  char id;
}

function sorting(struct human person)
{
  struct human temp
  int i, unsorted;

  do{
     unsorted = 0;
     for(i = o; i<count-1; i++)
     {
        if(strcmp(person[i].name, person.name) > 0)
        {
          temp = person[i];
          person[i] = person[i+1];
          person[i+1] = temp;
          unsorted = 1;
        }
     }while(unsorted);
}

Upvotes: 1

Views: 249

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993881

First, it would help to break out your comparison function into its own function:

int compare_people(struct human *person1, struct human *person2)
{
    return strcmp(person1->name, person2->name);
}

Then, you can more easily change the logic to compare ID if the name is equal:

int compare_people(struct human *person1, struct human *person2)
{
    int d = strcmp(person1->name, person2->name);
    if (d == 0) {
        return person2->id - person1->id;
    } else {
        return d;
    }
}

Upvotes: 4

Related Questions