在C中按结构排序数组

时间:2013-04-11 21:00:00

标签: c arrays sorting struct

我试图按分数排序,但它只对分数进行排序,ID保持不变。在对其进行排序时,如何将ID与其分数相匹配?

void sort(struct student* students, int n)
{

    int temp=0,j,i;

    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            if(students[j].score >students[j+1].score)
            {
                temp=students[j].score;
                students[j].score =students[j+1].score;
                students[j+1].score = temp;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

temp是一个整数,但它必须是student类型的结构。

试试这个:

void sort(struct student* students, int n) {
    int j,i;

    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            if(students[j].score >students[j+1].score)
            {
                struct student temp = students[j];
                students[j] =students[j+1];
                students[j+1] = temp;
            }
        }
    }
}