易百教程

编写程序使用冒泡排序结构体数组

结构体显示按照首先列出的最高分数进行排序。

提示
对结构数组进行排序就像排序任何其他数组一样。可以交换结构数组元素,就像交换任何数组元素一样。

实现代码

#include <stdio.h>

int main()
{
    struct scores
    {
        char name[32];
        int score;
    };
    struct scores player[4];
    struct scores temp;
    int x, a, b;

    for (x = 0; x < 4; x++)
    {
        printf("Enter player %d: ", x + 1);
        scanf("%s", player[x].name);
        printf("Enter their score: ");
        scanf("%d", &player[x].score);
    }

    for (a = 0; a < 4; a++)
        for (b = a + 1; b < 4; b++)
            if (player[a].score < player[b].score)
            {
                temp = player[a];
                player[a] = player[b];
                player[b] = temp;
            }

    puts("Player Info");
    printf("#\tName\tScore\n");
    for (x = 0; x < 4; x++)
    {
        printf("%d\t%s\t%5d\n",
            x + 1, player[x].name, player[x].score);
    }
    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

Enter player 1: 12
Enter their score: 12
Enter player 2: 22
Enter their score: 22
Enter player 3: 23
Enter their score: 23
Enter player 4: 24
Enter their score: 24
Player Info
#       Name    Score
1       24         24
2       23         23
3       22         22
4       12         12