蓝桥杯 ALGO-141 算法训练 P1102

xiaoxiao2021-02-28  92

定义一个学生结构体类型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> #include<string.h> struct Student { char name[100]; char sex[100]; int age; int score; }; int main() { int i,j,n,c,d; char a[100]; char b[100]; scanf("%d",&n); struct Student edu[n]; for(i=0;i<n;i++) { scanf("%s %s %d %d",&edu[i].name,&edu[i].sex,&edu[i].age,&edu[i].score); } for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(edu[j].score>edu[j+1].score) { strcpy(a,edu[j+1].name); strcpy(edu[j+1].name,edu[j].name); strcpy(edu[j].name,a); strcpy(b,edu[j+1].sex); strcpy(edu[j+1].sex,edu[j].sex); strcpy(edu[j].sex,b); c=edu[j+1].age; edu[j+1].age=edu[j].age; edu[j].age=c; d=edu[j+1].score; edu[j+1].score=edu[j].score; edu[j].score=d; } } } for(i=0;i<n;i++) { printf("%s %s %d %d\n",edu[i].name,edu[i].sex,edu[i].age,edu[i].score); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-67602.html

最新回复(0)