题目描述:
查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
例示:jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
Tom 70
jack 70
peter 96
输入描述:
输入多行,先输入要排序的人的个数,然后分别输入他们的名字和成绩,以一个空格隔开
输出描述:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
思路一:
import java.util.*;
class Student
{
String name;
int grade;
public Student()
{
this.name = "";
this.grade = 0;
}
}
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int n = scanner.nextInt();
int flag = scanner.nextInt();
scanner.nextLine();
Student[] students = new Student[n];
for (int i = 0; i < n; i++)
{
String str = scanner.nextLine();
String[] strs = str.split(" ");
students[i] = new Student();
students[i].name = strs[0];
students[i].grade = Integer.valueOf(strs[1]);
}
if (flag == 0)
{
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.grade - o1.grade;
}
});
}
else
{
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.grade - o2.grade;
}
});
}
for (int i = 0; i < n; i++)
System.out.println(students[i].name + " " + students[i].grade);
}
}
}
思路二:
import java.util.*;
class Student
{
String name;
int grade;
public Student()
{
this.name = "";
this.grade = 0;
}
}
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
int n = scanner.nextInt();
int flag = scanner.nextInt();
scanner.nextLine();
Student[] students = new Student[n];
for (int i = 0; i < n; i++)
{
String str = scanner.nextLine();
String[] strs = str.split(" ");
students[i] = new Student();
students[i].name = strs[0];
students[i].grade = Integer.valueOf(strs[1]);
}
if (flag == 0)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n - 1; j++)
if (students[j].grade < students[j + 1].grade)
swap(students, j, j + 1);
}
else
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n - 1; j++)
if (students[j].grade > students[j + 1].grade)
swap(students, j, j + 1);
}
for (int i = 0; i < n; i++)
System.out.println(students[i].name + " " + students[i].grade);
}
}
public static void swap(Student[] students, int m, int n)
{
Student stu = new Student();
stu = students[m];
students[m] = students[n];
students[n] = stu;
}
}