Alex Mohr
Alex Mohr

Reputation: 719

How do you sort an array based on more than one field in C?

I have an array of events, and I would like to sort them based on their year, then by month for each year, then by day for each month, then by hour for each day.

typedef struct {
    struct tm start;
    struct tm end;
} event;
...
event events[100];

I only need to worry about sorting with the start date. I've been struggling with this for hours...

Upvotes: 0

Views: 77

Answers (1)

unwind
unwind

Reputation: 399813

The same way you do any sorting on multiple keys: one at a time, in your desired order of priority.

A qsort() callback could look something like this:

static int event_compare(const void *a, const void *b)
{
  const event *ae = a, *be = b;

  if(ae->start.tm_year < be->start.tm_year)
    return -1;
  else if(ae->start.tm_year > be->start.tm_year)
    return 1;
  /* Years are equal, try to solve that by checking month. */
  if(ae->start.tm_month < be->start.tm_month)
    return -1;
  else if(ae->start.tm_month > be->start.tm_month)
    return 1;
  /* Months are equal, go on with day, and so on. */
}

Upvotes: 5

Related Questions