简体   繁体   English

对长数组进行排序

[英]Sort long array of structs

So I have an Array of Structs with Months and Days on it, and I want to sort it so the first struct will hold the day 1 of the month 1, the second the day 2 of the mont 1 and so on. 所以我有一个带有月和日的结构数组,我想对其进行排序,因此第一个结构将保留第1个月的第1天,第二个结构将保留mont 1的第2天,依此类推。

I am trying to do this by storing the correct array in a temporal array and then replacing them. 我试图通过在时间数组中存储正确的数组,然后替换它们来做到这一点。

My problem is, to do the following, the only algorithm I could made crashes my prompt and gives me a segmetation fault. 我的问题是,执行以下操作,我可以使唯一的算法崩溃,并出现隔离错误。 By now i'm confused enough not to know if my logic is wrong or i'm doing it in a too complex way for the program to work. 到现在为止,我很困惑,无法知道我的逻辑是否错误,或者我是否以太复杂的方式使程序无法正常工作。

Here is the function with my cod 这是我的鳕鱼的功能

void sortData(struct StructData data[], int size){

    int i=0,x=0,z=0,v_day=0,v2_day=0;
    struct StructData temp[sz];

    for (i=0;i!=12;i++){

        for (x=0;x!=12;x++){

            if (data[x].month == i+1){

                for (v=0;v!=31;v++){

                    for(v2=0;v2!=31;v2++){

                        if (data[v2].day == v+1){

                            temporal[z] = data[v2];
                            z=z+1;

                        }
                    }
                }
            } 
        }
    }

    i=0;


    for (i=0;i!=size;i++){
        data[i] = temporal[i];
    }
}

There is probably a better way to do this, I just don't see it. 可能有更好的方法来执行此操作,我只是看不到它。

You probably want to use qsort with a compare function something like this: 您可能希望将qsort与比较函数一起使用,如下所示:

int comp (const void * elem1, const void * elem2)
{
    struct StructData f = *((struct StructData*)elem1);
    struct StructData s = *((struct StructData*)elem2);
    if (f.day > s.day) return  1;
    if (f.day < s.day) return -1;
    return 0;
}

Keep in mind that all this code probably won't work. 请记住,所有这些代码可能无法正常工作。 Haven't written C code in a long time so this is more like theoretical code. 很久没有写C代码了,所以它更像是理论代码。 Basically you want to be looking at the structures from the array and comparing their values inside the function somehow. 基本上,您想查看数组中的结构,并以某种方式在函数中比较它们的值。

Sort on months, if they are same sort on days. 如果按天排序,则按月排序。 Use any sorting algo. 使用任何排序算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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