题目1196:成绩排序

9 篇文章 0 订阅
7 篇文章 0 订阅

练习一下基本的排序方法:题目来源九度oj

算法的设计思想:结构体存储学号和成绩,结构体的二级排序。第一种方法简单的泡排序,成绩大的在后面;成绩相等时学号大的在后面。

                               第二种方法用sort排序。

题目:

题目描述:

用一维数组存储学号和成绩,然后,按成绩排序输出。

输入:

输入第一行包括一个整数N(1<=N<=100),代表学生的个数。
接下来的N行每行包括两个整数p和q,分别代表每个学生的学号和成绩。

输出:

按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。
如果学生的成绩相同,则按照学号的大小进行从小到大排序。

样例输入:
3
1 90
2 87
3 92
样例输出:
2 87
1 90
3 92
方法一代码实现:

         

#include <iostream>
#include <stdio.h>
using namespace std;

struct node
{
    int num;
    int score;
} stu[101] ;
int main()
{
    int n;
    int i,j;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=0; i<n; i++)
        {
            scanf("%d %d",&stu[i].num,&stu[i].score);
        }
        for(i=0; i<n; i++)
        {
            for(j=0; j<n-1-i; j++)
            {
                if((stu[j].score>stu[j+1].score) || (stu[j].score==stu[j+1].score)&&(stu[j].num>stu[j+1].num))
                {
                    int temp=stu[j].score;
                    stu[j].score=stu[j+1].score;
                    stu[j+1].score=temp;
                    temp=stu[j].num;
                    stu[j].num=stu[j+1].num;
                    stu[j+1].num=temp;
                }
            }
        }
        for(i=0; i<n; i++)
        {
            printf("%d %d\n",stu[i].num,stu[i].score);
        }
    }
    return 0;
}

方法二代码实现:

#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;

struct node
{
    int num;
    int score;

    bool operator < (const node& other)const
    {
        if(score!=other.score) return score <other.score;
        return num < other.num;
    }
} stu[101] ;
int main()
{
    int n;
    int i,j;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=0; i<n; i++)
        {
            scanf("%d %d",&stu[i].num,&stu[i].score);
        }
        sort(stu,stu+n);
        for(i=0; i<n; i++)
        {
            printf("%d %d\n",stu[i].num,stu[i].score);
        }
    }
    return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值