简体   繁体   中英

Selection Sort for struct

i'm having an issue with the logic surrounding using selection sort for a struct array. for example say this is my struct :

struct data {
    int month
    int day
    ..
    .. }

now what I want to do is sort the months and days. I believe I know how to do this for the months, yet am having a hard time understanding how to implement this for days. here is my code for the months so far:

void sortData(struct Data yearData[], int sz)
    int i, j, m;
    int temp;

    for (i = 0; i < sz; i++) {
        m = i;
        for (j = i + 1; j < sz; j++)
            if (yearData[j].month < yearData[m].month) {
                m = j;
             }

        if (m != i) {
            temp = yearData[i].month;
            yearData[i].month = yearData[m].month;
            yearData[m].month = temp;
        }
    }
}

I think i want to check to see if the months are the same then look at days and sort them as well. I just don't know if it would be correct to add another iteration to this sort. Thanks!

Try this:

...
if((yearData[j].month < yearData[m].month) || 
   ((yearData[j].month == yearData[m].month) && 
    (yearData[j].day < yearData[m].day))) {
    m = j;
}
...

However, I am not sure I understand your swap. You should swap the entire struct, not the its members one by one. Consider this:

if (m != i) {
  struct Data tmp = yearData[i];
  yearData[i] = yearData[m];
  yearData[m] = tmp;
}

Make a comparison function, then use its result. The comparison function should return 0 if the structs are equal, -1 if the left should go first, +1 if the right should go first.

It will look something like:

int yearDataCmp(struct Data left, struct Data right) {
    if ( left.month < right.month ) { return -1; }
    if ( left.month > right.month ) { return  1; }
    if ( left.day   < right.day   ) { return -1; }
    if ( left.day   > right.day   ) { return  1; }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM