问题描述: 查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
例示:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
Tom 70
jack 70
peter 96
知识点: 排序
题目来源: 内部整理
练习阶段: 中级
运行时间限制: 10Sec
内存限制: 128MByte
输入:
输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开
用户名字,字符串,非空串,长度不超过20;
成绩,整数,范围【0,100】
输入排序方式,0或1,0表示成绩从高到低方式输出名字和成绩,1表示成绩从低到高方式输出名字和成绩
输出:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
样例输入: 3
0
fang 90
yang 50
ning 70
样例输出: fang 90
ning 70
yang 50
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class SoreSort {
static SoreSort ss = new SoreSort();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int m = scan.nextInt();
int check = scan.nextInt();
TreeSet<Student1> ts = new TreeSet<Student1>();
TreeSet<Student2> ts2 = new TreeSet<Student2>();
while(m>0){
String str = scan.next();
int num = scan.nextInt();
Student1 s1 = ss.new Student1(str,num);
Student2 s2 = ss.new Student2(str, num);
ts.add(s1);
ts2.add(s2);
m--;
}
if(check == 0)
downSort(m,ts);
else
upSort(m,ts2);
}
private static void upSort(int m, TreeSet<Student2> ts2) {
Iterator<Student2> it = ts2.iterator();
while (it.hasNext()) {
Student2 s2 = it.next();
System.out.println(s2.getName() + " " + s2.getscore());
}
}
private static void downSort(int m, TreeSet<Student1> ts) {
Iterator<Student1> it = ts.iterator();
while (it.hasNext()) {
Student1 s1 = it.next();
System.out.println(s1.getName() + " " + s1.getscore());
}
}
private class Student2 implements Comparable{
private String name;
private int score;
public Student2(String str, int num) {
this.name = str;
this.score = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getscore() {
return score;
}
public void setscore(int score) {
this.score = score;
}
@Override
public int compareTo(Object o) {
Student2 s = (Student2) o;
if(this.score > s.score)
return 1;
else if(this.score == s.score){
if(this.name.compareTo(s.name) > 0)
return 1;
else if(this.name.compareTo(s.name) < 0)
return -1;
else
return 0;
}
return -1;
}
}
private class Student1 implements Comparable{
private String name;
private int score;
public Student1(String str, int num) {
this.name = str;
this.score = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getscore() {
return score;
}
public void setscore(int score) {
this.score = score;
}
@Override
public int compareTo(Object o) {
Student1 s = (Student1) o;
if(this.score > s.score)
return -1;
else if(this.score == s.score){
if(this.name.compareTo(s.name) > 0)
return 1;
else if(this.name.compareTo(s.name) < 0)
return -1;
else
return 0;
}
return 1;
}
}
}