华为机试---成绩排序



题目描述

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
      都按先录入排列在前的规则处理。

   例示:
   jack      70
   peter     96
   Tom       70
   smith     67

   从高到低  成绩            
   peter     96    
   jack      70    
   Tom       70    
   smith     67    

   从低到高

   smith     67  

   Tom       70    
   jack      70    
   peter     96      


输入描述:

输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开



输出描述:

按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开


输入例子:
3
0
fang 90
yang 50
ning 70

输出例子:
fang 90
ning 70
yang 50
 
 
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
//存储每个学生的基本信息
class Info{
 int index;//录入序号
 String name;//姓名
 int score;//成绩
 //构造方法
 public Info(int index , String name , int score){
  this.index = index; 
  this.name = name;
  this.score = score;
 } 
}
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);        
        while(scan.hasNext()){
         List<Info> list = new ArrayList<Info>();//每次输入数据前都要清空
            int stu_num = scan.nextInt();
            int sort_way = scan.nextInt();
            for(int i = 0 ; i < stu_num ; i++){
             String name = scan.next();
             int score = scan.nextInt();
             list.add(new Info(i , name , score));
            }
            //sort_way=0降序排列
            if(sort_way == 0){
             //自定义比较器
             Collections.sort(list , new Comparator<Info>() {     
     public int compare(Info o1, Info o2) {
      if(o1.score != o2.score){
       //后面减去前面,如果相减为负,表示降序
       return o2.score - o1.score;
      }else{
       //分数相等,按照序号的优先顺序保存
       //前面减去后面,如果相减为负,表示升序
       return o1.index - o2.index;
      }      
     }              
    });             
            }else{
            //sort_way=1升序排列
             Collections.sort(list , new Comparator<Info>(){
              public int compare(Info o1, Info o2){
               if(o1.score != o2.score){
                return o1.score - o2.score;
               }else{
                return o1.index - o2.index; 
               }
              }
             });
            } 
            //打印信息
            for(Info stu : list){
             System.out.println(stu.name + " " + stu.score);
            }
//            list.clear();//清空列表
        }
        scan.close();
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值