C语言冒泡排序法将学生成绩按从小到大顺序排列

定义一个学生结构体类型student,包括4个字段,姓名、性别、年龄和成绩。然后在主函数中定义一个结构体数组(长度不超过1000),并输入每个元素的值,程序使用冒泡排序法将学生按照成绩从小到大的顺序排序,然后输出排序的结果。
  输入格式:第一行是一个整数N(N<1000),表示元素个数;接下来N行每行描述一个元素,姓名、性别都是长度不超过20的字符串,年龄和成绩都是整型。
  输出格式:按成绩从小到大输出所有元素,若多个学生成绩相同则成绩相同的同学之间保留原来的输入顺序。
输入格式
  3
  Alice female 18 98
  Bob male 19 90
  Miller male 17 92
输出格式
  Bob male 19 90
  Miller male 17 92
  Alice female 18 98
回答后会追加悬赏

#include <stdio.h>

struct student
{
char name[20];
char sex[20];
int age;
int score;
};

void sort(struct student data[], int size)
{
/*冒泡排序*/
int x,y;
    struct student temp;

for(x=0;x<size-1;x++)
for(y=0;y<size-1-x;++y)
if(data[y].score>data[y+1].score)
{
temp=data[y+1];
data[y+1]=data[y];
data[y]=temp;
}

}
int main()
{
    int qty, counter;
struct student data[1000];

    scanf("%d",&qty);
for(counter=0;counter<qty;++counter)
scanf("%s%s%d%d",data[counter].name,data[counter].sex,&data[counter].age,&data[counter].score);
    
sort(data,qty);

for(counter=0;counter<qty;++counter)
printf("%s %s %d %d\n",data[counter].name,data[counter].sex,data[counter].age,data[counter].score);


    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-25
#include <stdio.h>
#include <string.h>

struct student
{
char name[20];
char gender[20];
int age;
int score;
};

void bubble_sort(struct student a[],int n);
 
void bubble_sort(struct student a[],int n) //n为数组a的元素个数
{
    int i, j;
struct student temp;
    for (j = 0; j < n - 1; j++)
        for (i = 0; i< n - 1 - j; i++)
        {
            if (a[i].score > a[i + 1].score) //数组元素大小按升序排列
            {
strcpy(temp.name, a[i].name);
strcpy(temp.gender, a[i].gender);
                temp.age = a[i].age;
temp.score = a[i].score;

                strcpy(a[i].name, a[i + 1].name);
strcpy(a[i].gender, a [i + 1].gender);
a[i].age = a[i + 1].age;
a[i].score = a[i + 1].score;

strcpy(a[i + 1].name, temp.name);
strcpy(a[i + 1].gender, temp.gender);
a[i + 1].age = temp.age;
a[i + 1].score = temp.score;
            }
        }
}

int main()
{
struct student stu[1000];
int i;
int n;
printf("how many student information do you want to input: ");
scanf("%d", &n);

for (i = 0; i < n; i++)
{
scanf("%s %s %d %d", stu[i].name, stu[i].gender, &stu[i].age, &stu[i].score);
}

bubble_sort(stu, n);

printf("After bubble sort by score:\n");
    for (i = 0;i < n; i++)
    {
        printf("%s %s %d %d\n", stu[i].name, stu[i].gender, stu[i].age, stu[i].score);
    }

return 0;
}

本回答被提问者和网友采纳
相似回答