题解 | #成绩排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int sort = sc.nextInt();//排序标记
Student[] arr = new Student[n];
for (int i = 0; i < n; i++) {
String name = sc.next();
int score = sc.nextInt();
arr[i] = new Student(name, score);
}
//排序,冒泡排序(稳定排序)
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if(sort==1){
if (arr[j].score > arr[j + 1].score) { //升序
Student temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}else {
if (arr[j].score < arr[j + 1].score) { //降序
Student temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
for (Student student : arr) {
System.out.println(student.name + " " + student.score);
}
}
}
}
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public Student() {
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int sort = sc.nextInt();//排序标记
Student[] arr = new Student[n];
for (int i = 0; i < n; i++) {
String name = sc.next();
int score = sc.nextInt();
arr[i] = new Student(name, score);
}
//排序,冒泡排序(稳定排序)
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if(sort==1){
if (arr[j].score > arr[j + 1].score) { //升序
Student temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}else {
if (arr[j].score < arr[j + 1].score) { //降序
Student temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
for (Student student : arr) {
System.out.println(student.name + " " + student.score);
}
}
}
}
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public Student() {
}
}