-1

i need to make a calender (like a to-do list) and i need to sort the months in it.

i have a struct :

typedef struct
{
    char name[3];
    int month_num;
    int day_num;
    int day_size; // amount of days that are field in with tasks.
    char task[40];

}month; // each month contains a name, its num in the calendar and days.

in order to sort the months, so that it will be easier, i decided to sort it by thier numbers. what i mean is that im calling Jan as the number 1, Feb as the number 2, etc. but since i have the struct i kinda lost in the way with all the names and all the elemnts.

i manged to give all the months thier numbers: (it's a little bit long, so i'll show the few first)

    if (strcmp(mName, "jan") == 0)
{
    mon[monthcounter].month_num = 1;
}
else if (strcmp(mName, "feb") == 0)
{
    mon[monthcounter].month_num = 2;
}
else if (strcmp(mName, "mar") == 0)
{
    mon[monthcounter].month_num = 3;
}
else if (strcmp(mName, "apr") == 0)
{
    mon[monthcounter].month_num = 4;
}
else
{
    printf("Invalid month\n");
}
//etc.

and now to make to sorting it self i've lost in the way. ( i do know how to make a regular swap function that recieves 2 intgeres or with an array, but i asume that here it is not the same...)

i'll really apreciate the help!

lili
  • 45
  • 6

2 Answers2

0

You're absolutely right - it is a simple swap function. The easiest way to solve your problem would be to use that function to get the integer values of the months, sort them, and then use a new function to convert them back.

Assuming that you make sure that month_num is between 0 and 11:

static const char *months[] = { "jan", "feb", ... };
return months[month_num];
Tom
  • 522
  • 3
  • 13
  • 1
    `static const char *months[] = { "jan", "feb", ... };` then validate the month number `n` as in-range (0..11) and simply `return months[n];` no sense in littering the code with 12 if-clauses where *one* will do. – WhozCraig Jan 27 '15 at 12:20
  • Certainly true. I was trying to draw a parallel, although, with hindsight, that probably isn't the best approach. – Tom Jan 27 '15 at 12:21
-1

The standard way for this would be to use C library function

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

I think you should be able to write code using that. You need to write a comparator function that "compares" two whatever you are comparing. In your case you are comparing the month structs, on the basis of month_num. So the comparator function in pseudo code

int compar (a, b)
{

    if(a.month_num > b.month_num)
        return 0 or 1; don't remember which one. 
    // write rest of the conditions. 
} 
Amit
  • 1,836
  • 15
  • 24