在Java中排序似乎没有C++中那么方便,搜索了很久看了很多文章,大概都是说要用Arrays或ArrayList或List或Collection等来实现,最头疼的是源代码要分开多个文件(这应该是一个好习惯,可是ACM只允许提交一个源文件)。
最终在这篇文章的提示下依葫芦画瓢,源代码在一个文件中就可以了,对于一些不太复杂的情况还是挺好的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import java.util.Arrays; import java.util.Scanner; class Student implements Comparable { String name; int gpa; public int compareTo(Object o) { Student s = (Student) o; if (this.gpa == s.gpa) return this.name.compareTo(s.name); if (this.gpa < s.gpa) return -1; else if (this.gpa == s.gpa) return 0; else return 1; } } public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Student[] s = new Student[n]; for (int i = 0; i != n; ++i) { s[i] = new Student(); s[i].name = in.next(); s[i].gpa = in.nextInt(); } Arrays.sort(s); for (Student ss : s) { System.out.println(ss.name); System.out.println(ss.gpa); } } } |
比如输入是:
4
icycandy 40
icycandy 50
nicyun 40
ybbaigo 50
输出如下:
icycandy
40
nicyun
40
icycandy
50
ybbaigo
50











