试题 算法训练 P1102
题目描述:
资源限制
时间限制:1.0s 内存限制:256.0MB
定义一个学生结构体类型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
此题排序,按照结构体中的属性score去排序。
AC代码:
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
struct node
{
char name[10];
char sex[7];//注意,字符串长度一定要是正确的
int age;
int score;
}student[1000];
int main()
{
int n,i,j;
cin>>n;
for(i=0;i<n;i++)
{
cin>>student[i].name>>student[i].sex>>student[i].age>>student[i].score;
}
for(i=0;i<n-1;i++)//只按照score的属性去排序
{
for(j=0;j<n-i-1;j++)
{
if(student[j].score>student[j+1].score)
swap(student[j],student[j+1]);
}
}
for(i=0;i<n;i++)
{
cout<<student[i].name<<" "<<student[i].sex<<" "<<student[i].age<<" "<<student[i].score<<endl;
}
return 0;
}