题目描述
查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
例示:
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();
}
}
243

被折叠的 条评论
为什么被折叠?



