zoukankan      html  css  js  c++  java
  • 笔试面试算法题解之华为-成绩排序

    笔试面试算法题解之华为-成绩排序

    题目描述

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

    输入描述

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

    输出描述

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

    思路剖析:

    先进行成绩排序,然后在进行成绩相同的时候,学好排序就行。

    输入例子:

    3
    1 90
    2 87
    3 92
    

    输出例子:

    2 87
    1 90
    3 92
    

    代码

    #include<iostream>
    #include<cstring>
    #include<malloc.h>
    #include<fstream>
    #include<cstdio>
    using namespace std;
    
    typedef struct student{
        int id;
        int score;
    };
    
    
    int main()
    {
        freopen("debug\in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
        freopen("debug\out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
        int n;
        cin>>n;
        student *stu;
        stu=(student*)malloc((n+50)*sizeof(student));
        for(int i=0;i<n;++i)
        {
            cin>>stu[i].id>>stu[i].score;
        }
        for(int i=0;i<n;++i)
        {
            for(int j=i;j<n;j++)
            {
                if(stu[j].score<stu[i].score)
                {
                    student temp;
                    memcpy(&temp,&stu[i],sizeof(student));
                    memcpy(&stu[i],&stu[j],sizeof(student));
                    memcpy(&stu[j],&temp,sizeof(student));
                }
            }
        }
        for(int i=0;i<n;++i)
        {
            for(int j=i;j<n;j++)
            {
                if((stu[j].score==stu[i].score)&&(stu[j].id<stu[i].id))
                {
                    student temp;
                    memcpy(&temp,&stu[i],sizeof(student));
                    memcpy(&stu[i],&stu[j],sizeof(student));
                    memcpy(&stu[j],&temp,sizeof(student));
                }
            }
        }
        for(int i=0;i<n;++i)
        {
            cout<<stu[i].id<<' '<<stu[i].score<<endl;
        }
        return 0;
    }
    
    
  • 相关阅读:
    C# 利用 Geckofx60 实现下载
    C# 线程 线程池
    C# DateTime 与 String 格式转换
    C# WPF 获取程序路径
    C# 计时器 Timer 介绍
    获取远程图片并把它保存到本地
    php sql 过滤
    PHP如何生成伪静态
    用php获取客户端IP地址的方法
    php过滤危险html代码
  • 原文地址:https://www.cnblogs.com/xzmds/p/5121961.html
Copyright © 2011-2022 走看看