0

有人可以帮我解决C中的这个问题吗?我需要按字母顺序对排行榜进行排序,并且按分数排序。我atoi()用于将字符串转换为整数,但名称保持在它们留下的顺序。这是排序的功能:

void bubbleSort2(int arr[], int n)
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
            }
        }
    }
}

void sortScores() {
    FILE* fp = openFile();
    int x[128];
    char line[128][20];
    int i = 0, j = 0;
    int tot = 0;
    while (fgets(line[i], 20, fp))
    {
        line[i][strlen(line[i]) - 1] = '\0';
        i++;
    }
    tot = i;
    for (int i = 0; i < tot; i++)
    {   
        char* sep = strchr(line[i], ' ');
        *sep = '\0';
        x[i] = atoi(sep + 1);
    }
    bubbleSort2(x, tot);
    printf("Sorted by scores:\n");
    for (int i = 0; i < tot; i++)
    {
        printf("%s %d\n", line[i],x[i]);
    }
    fclose(fp);
}

这是输出:

Sorted alphabetical:
Branimir 100
Branimir 700
Brekalo 100
Hrvoje 350
Ilija 0
Ilija 50
Marin 100
Marin 400
Marko 0
Marko 300
Matej 0
Matej 900
Nikola 0
Pero 100
Pero 150
Ramal 100
Simun 550
Skoric 0

Sorted by scores:
Ramal 900
Ilija 700
Ilija 550
Pero 400
Pero 350
Nikola 300
Marko 150
Marin 100
Marko 100
Marin 100
Matej 100
Branimir 100
Matej 50
Branimir 0
Brekalo 0
Skoric 0
Hrvoje 0
Simun 0

Matej 应该排在第一位,而不是 Ramal。我希望你能帮我解决这个问题。

4

2 回答 2

0

您需要使用结构来存储数据。

#define MAXNAME 20

typedef struct
{
    int score;
    char name[MAXNAME];
}student;

void bubbleSort2(student arr[], size_t n)
{
    /* ..... */
    if (arr[d].score < arr[d + 1].score)

    /* etc etc */
}
于 2021-06-08T19:16:19.173 回答
0

您只是对值进行排序,而不是对其名称进行排序。

还要在排序函数中更改char line[128][20]的索引。

在主函数中 pass bubbleSort2(x, tot,line);

在冒泡排序中

void bubbleSort2(int arr[], int n,char line[128][20])
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
                swap(line[d],line[d+1]);
            }
        }
    }
}

希望能帮助到你 :)

于 2021-06-08T19:14:34.970 回答