首页 > 试题广场 >

成绩排序

[编程题]成绩排序
  • 热度指数:233743 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给出的 n 条姓名和成绩信息,根据指定的排序方式按成绩升序或降序排列并输出。
\hspace{15pt}特别的,成绩相同的同学需要保持输入的先后顺序进行排序。可能存在多条信息的学生姓名一致。

输入描述:
\hspace{15pt}第一行输入一个整数 n \left(1 \leqq n \leqq 200\right) 代表学生人数。
\hspace{15pt}第二行输入一个整数 op \left(0 \leqq op \leqq 1\right) 代表排序方式,其中,0 表示按成绩降序,1 表示按成绩升序。
\hspace{15pt}此后 n 行,第 i 行依次输入:
\hspace{23pt}\bullet\,一个长度为 1 \leqq {\rm len}(s_i) \leqq 20、由大小写字母构成的字符串 s_i 代表第 i 个学生的姓名;
\hspace{23pt}\bullet\,一个整数 a_i \left(0 \leqq a_i \leqq 100\right) 代表这个学生的成绩。


输出描述:
\hspace{15pt}根据输入的排序方式,按照成绩升序或降序输出所有学生的姓名和成绩。对于每一名学生,新起一行。输出学生的姓名和成绩,用空格分隔。
示例1

输入

3
0
fang 90
yang 50
ning 70

输出

fang 90
ning 70
yang 50

说明

\hspace{15pt}在这个样例中,op = 0,因此按成绩降序排序。
示例2

输入

4
1
fang 90
yang 50
ning 70
yang 70

输出

yang 50
ning 70
yang 70
fang 90

说明

\hspace{15pt}在这个样例中,op = 1,因此按成绩升序排序。

备注:
本题已于下方时间节点更新,请注意题解时效性:
1. 2025-05-16 更新题面。
2. 2025-01-09 更新题面。
面向对象编程。。。
import java.util.*;
import java.util.stream.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int num = Integer.valueOf(in.nextLine());
            int sort = Integer.valueOf(in.nextLine());
            List<Student> list = new ArrayList<>();
            while(num>0){
                String[] inputs = in.nextLine().split(" ");
                list.add(new Student(inputs[0],Integer.valueOf(inputs[1])));
                num--;
            }

            list = list.stream().sorted((a,b)->{
                if(sort == 0 ){
                    return b.score-a.score;
                } else {
                    return a.score-b.score;
                }
            }).collect(Collectors.toList());

            list.forEach(o -> System.out.println(o.name+" "+o.score));
        }
    }


   static class Student{
        String name;
        int score;

        public Student(String name,int score){
            this.name= name;
            this.score=score;
        }
    }
}



发表于 2025-06-20 20:52:35 回复(0)

一、容易想到的方法,封装对象。

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int total = in.nextInt();
        int order = in.nextInt();
        List<Stu> list = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            String name = in.next();
            int score = in.nextInt();
            Stu stu = new Stu(name, score);
            list.add(stu);
        }

        if (order == 0) {
            // 0 降序
            Collections.sort(list, Comparator.reverseOrder());
        } else if (order == 1) {
            // 1 升序
            Collections.sort(list);
        }

        list.forEach(stu -> System.out.println(stu.getName() + " " + stu.getScore()));

    }

    private static class Stu implements Comparable<Stu> {
        private String name;
        private int score;

        Stu(String name, int score) {
            this.name = name;
            this.score = score;
        }

        int getScore() {
            return this.score;
        }

        String getName() {
            return this.name;
        }

        public int compareTo(Stu o) {
            if (o == null) {
                return 1;
            }
            return this.getScore() - o.getScore();
        }
    }
}

二、其实List嵌套List也可以被排序

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int total = in.nextInt();
        int order = in.nextInt();
        List<List> list = new ArrayList<>();

        for (int i = 0; i < total; i++) {
            String name = in.next();
            int score = in.nextInt();
            List l = new ArrayList<>();
            l.add(name);
            l.add(score);
            list.add(l);
        }

        if (order == 0) {
            // 0 降序
            Collections.sort(list, (o1, o2) -> (int) o2.get(1) - (int) o1.get(1));
        } else if (order == 1) {
            // 1 升序
            Collections.sort(list, (o1, o2) -> (int) o1.get(1) - (int) o2.get(1));
        }

        list.forEach(l -> System.out.println(l.get(0) + " " + l.get(1)));
    }
}
发表于 2025-05-29 10:19:49 回复(0)
这题目存在坑,题目不说分数相同情况下要按照输入顺序来排序。
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int op = sc.nextInt();
        String [][]arr = new String[n][3];
        for (int i = 0; i < n; i++) {
            String s = sc.next();
            String age = sc.next();
            arr[i] = new String[]  {s, age, "" + i};
        }
        Arrays.sort(arr, new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                int r = Integer.parseInt(o1[1])  - Integer.parseInt(o2[1]);
                if(r==0){
                    // 如果成绩相同就按照原始输入顺序排序
                    return Integer.parseInt(o1[2])  - Integer.parseInt(o2[2]);
                } else {
                    // 注意op==0时要倒序排序
                    return op==0? -r : r;
                }
            }
        });
        for (String[] s : arr) {
            System.out.println(s[0] + " " + s[1]);
        }
    }


发表于 2025-05-08 22:47:47 回复(1)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int num = in.nextInt();
        int order = in.nextInt();

        List<Map.Entry<String,Integer>> list = new ArrayList<>();

        while (in.hasNext()) { // 注意 while 处理多个 case
            String name = in.next();
            int g = in.nextInt();
            Map<String,Integer> map = new HashMap<>();
            map.put(name,g);
            Set<Map.Entry<String,Integer>> set =  map.entrySet();
            list.add(set.iterator().next());
        }

       
        if (order == 0) {
            // 降序
            list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
        } else {
            // 升序
            list.sort(Map.Entry.comparingByValue());
        }

        for (Map.Entry<String,Integer> m : list) {
            System.out.println(m.getKey() + " " + m.getValue());
        }
    }
}
发表于 2025-04-22 14:26:52 回复(0)
//思路使用归并排序对成绩进行排序,但成绩相同时,题目没给出比较方式,测试案例9未通过

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static String[][] studentMarks;
    static boolean op = true;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int b = in.nextInt();
            String c = in.nextLine();
            if(b != 0){
                op = false;
            }
            studentMarks = new String[a][2];
            for(int i = 0; i < a; i++){
                String studentMark = in.nextLine();
                studentMarks[i] = studentMark.split(" ");
            }
            merger(0,a-1);

            for(int i = 0; i < a; i++){
                System.out.println(studentMarks[i][0] + " " + studentMarks[i][1]);
            }

        }
    }

    public static void merger(int left, int right){
        if(left < right){
            int mid = left + (right - left) / 2;

            merger(left, mid);

            merger(mid+1,right);

            domerger(left, mid, right);
        }

    }

    public static void domerger(int left, int mid, int right){
        int n1 = mid - left + 1;
        int n2 = right - mid;
       

        String[][] l1 = new String[n1][2];
        String[][] l2 = new String[n2][2];
        for(int i = 0; i < n1; i++){
            l1[i] = studentMarks[left + i];
        }

        for(int i = 0; i < n2; i++){
            l2[i] = studentMarks[mid + i + 1];
        }

        int l = 0;
        int r = 0;
        int k = left;
        while(l < n1 && r < n2){
            if((Integer.valueOf(l1[l][1]) > Integer.valueOf(l2[r][1])) == op){
                studentMarks[k] = l1[l];
                l++;
            }else{
                studentMarks[k] = l2[r];
                r++;
            }
            k++;
        }

        while(l < n1){
            studentMarks[k] = l1[l];
            l++;
            k++;
        }

        while(r < n2){
            studentMarks[k] = l2[r];
            r++;
            k++;
        }
    }

}
发表于 2025-02-18 10:59:05 回复(0)

1 最初,使用HashMap存(名字,成绩),按成绩排序
2 但成绩相同时,名字无法按录入顺序排序
3 想到用List存储、排序,但List存不了(名字,成绩)两个值
4 百度一下,可自建一个类KV,包装下(名字,成绩)存入List   
【有点面向对象的味道了】
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int op = in.nextInt();
        List<KV> list = new ArrayList<>();
        while (n-- > 0) {
            list.add(new KV(in.next(),in.nextInt())); // 存入list
        }
        list.sort((o1,o2)->{ return op == 1 ? o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue());});  // 排序
        list.forEach(e-> {System.out.println(e.getKey() + " " + e.getValue());}); // 打印
    }

}
// 包装(名字,成绩)
class KV {
    private String key;
    private Integer value;
    public KV(String key, Integer value) {
        this.key = key;
        this.value = value;
    }
    public String getKey() {
        return this.key;
    }
    public Integer getValue() {
        return this.value;
    }
}


发表于 2025-01-28 13:32:59 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        // 读取学生人数
        int n = in.nextInt();

        // 读取排序方式
        int sortType = in.nextInt();

        // 创建学生数组
        String[] names = new String[n];
        int[] scores = new int[n];

        // 读取学生信息
        for (int i = 0; i < n; i++) {
            names[i] = in.next();
            scores[i] = in.nextInt();
        }

        // 两层循环实现冒泡排序
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if ((sortType == 0 && scores[j] < scores[j + 1]) || (sortType == 1 && scores[j] > scores[j + 1])) {
                    // 交换成绩
                    int tempScore = scores[j];
                    scores[j] = scores[j + 1];
                    scores[j + 1] = tempScore;
                    // 交换名字
                    String tempName = names[j];
                    names[j] = names[j + 1];
                    names[j + 1] = tempName;
                }
            }
        }
        // 输出排序后的学生信息
        for (int i = 0; i < n; i++) {
            System.out.println(names[i] + " " + scores[i]);
        }

        in.close();
    }
}

发表于 2024-10-19 11:52:16 回复(0)
// 算法复杂度O(nlogn)空间复杂度o(n);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int flag = Integer.parseInt(br.readLine());

        Map<Integer, List<String>> map = new HashMap<>();

        String str;
        while ((str = br.readLine()) != null && !str.isEmpty()) {
            String[] strs = str.split(" ");
            int key = Integer.parseInt(strs[1]);
            List<String> names = map.getOrDefault(key, new ArrayList<>());
            names.add(strs[0]);
            map.put(key, names);
        }

        int[] nums = new int[map.size()];
        int index = 0;

        for (int key : map.keySet()) {
            nums[index++] = key;
        }

        Arrays.sort(nums);

        if (flag == 1) {  // 升序输出
            for (int i : nums) {
                for (String name : map.get(i)) {
                    System.out.println(name + " " + i);
                }
            }
        } else {
            for (int i = nums.length - 1; i >= 0; i--) {
                int key = nums[i];
                for (String name : map.get(key)) {
                    System.out.println(name + " " + key);
                }
            }
        }
    }
}

发表于 2024-09-01 20:35:21 回复(0)
TreeMap, 成绩做key,, 值存名字的list
import java.util.Scanner; 
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int sort = in.nextInt();
            Comparator<Integer> comparator = sort == 0 ? (x, y) -> y - x : Integer::compareTo;
            Map<Integer, List<String>> map = new TreeMap<>(comparator);
            for (int i = 0; i < n; i++) {
                String name = in.next();
                int score = in.nextInt();
                map.computeIfAbsent(score, k -> new ArrayList<String>()).add(name);
            }
            map.forEach((k,v) -> {
                for (String s : v) {
                    System.out.println(s + " " + k);
                }
            });
        }
    }
}


发表于 2024-07-18 16:49:58 回复(0)

思路:利用桶排序

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int sum = in.nextInt();
        int sort = in.nextInt();
        //数组的角标即为成绩,利用桶排序
        Student[] stu = new Student[101];
        for (int i = 0; i < sum; i++) {
            String name = in.next();
            int score = in.nextInt();
            //每个类记录相同分数的所有名字
            if (stu[score] == null) {
                stu[score] = new Student(name);
            } else {
                stu[score].addName(name);
            }
        }
        //从小到大,正序输出student数组
        if (sort == 1) {
            for (int i = 0; i <= 100; i++) {
                if (stu[i] != null) {
                    //遍历每个类内部所有的名字
                    for (int j = 0; j < stu[i].point; j++) {
                        System.out.println(stu[i].name[j] + " " + i);
                    }
                }
            }
        //从大到小,倒序输出
        } else {
            for (int i = 100; i >= 0; i--) {
                if (stu[i] != null) {
                    for (int j = 0; j < stu[i].point; j++) {
                        System.out.println(stu[i].name[j] + " " + i);
                    }
                }
            }
        }

    }
}
//对每个分数建立名字列表,以保证相同成绩时,保持输入的顺序
class Student {
    String[] name = new String[200];
    //每个类内部维护记录名字的数组
    int point = 0;
    public Student(String name) {
        this.name[point++] = name;
    }
    public void addName(String name) {
        this.name[point++] = name;
    }
}
发表于 2024-07-08 22:06:16 回复(0)
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        Student.sortMethod = Integer.parseInt(in.nextLine());
        Student[] students = new Student[n];
        for (int i = 0; i < n; i++) {
            String[] s = in.nextLine().split(" ");
            students[i] = new Student(i, s[0], Integer.parseInt(s[1]));
        }
        Arrays.sort(students);
        for (Student student : students) {
            System.out.println(student.name + " " + student.score);
        }
    }
}

class Student implements Comparable<Student> {
    int i;
    String name;
    int score;
    public static int sortMethod;

    public Student(int i, String name, int score) {
        this.i = i;
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(Student o) {
        int s = Integer.compare(this.score, o.score);
        if (sortMethod == 0) {
            s = -s;
        }
        if (s != 0) {
            return s;
        }
        return Integer.compare(this.i, o.i);
    }
}
是很难看,但是过了啊(
发表于 2024-06-21 22:41:45 回复(0)
import java.util.*;

import static java.lang.Integer.parseInt;


class Person {
private String name;
private int score;

public Person(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
class PersonAgeComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o2.getScore()-o1.getScore() ;
}
}

public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
HashMap<Integer,String> map=new HashMap<>();

while(sc.hasNext()){
//人数
int n = parseInt(sc.nextLine());
//排序方式
int sort_way= parseInt(sc.nextLine());//1是升序,0是降序
//姓名编号,成绩
Person[] people=new Person[n];

for(int i=0;i<n;i++){
String[] nameAndScore = sc.nextLine().split(" ");
String name=nameAndScore[0];
int score=parseInt(nameAndScore[1]) ;
people[i]=new Person(name,score);
}
Arrays.sort(people,new PersonAgeComparator());
for(int i=0;i<n;i++){
System.out.println(people[i].getName() + " " +people[i].getScore());
}
}
}
}
编辑于 2024-04-12 15:31:44 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int flag = in.nextInt();

            List<String[]> list = new ArrayList();
            for (int i = 0; i < n; i++) {
                String[] arr = new String[2];
                arr[0] = in.next();
                arr[1] = in.next();
                list.add(arr);
            }



            if (flag == 0) {
                list.sort(new Comparator<String[]>() {
                    @Override
                    public int compare(String[] o1, String[] o2) {
                        if (Integer.valueOf(o1[1]) > Integer.valueOf(o2[1])) {
                            return -1;
                        } else if (Integer.valueOf(o1[1]) < Integer.valueOf(o2[1])) {
                            return 1;
                        }
                        return 0;
                    }
                });
                for (int i = 0; i < n; i++) {
                    System.out.println(list.get(i)[0] + " " + list.get(i)[1]);
                }
            } else if (flag == 1) {
                list.sort(new Comparator<String[]>() {
                    @Override
                    public int compare(String[] o1, String[] o2) {
                        if (Integer.valueOf(o1[1]) > Integer.valueOf(o2[1])) {
                            return 1;
                        } else if (Integer.valueOf(o1[1]) < Integer.valueOf(o2[1])) {
                            return -1;
                        }
                        return 0;
                    }
                });
                for (int i = 0; i < n; i++) {
                    System.out.println(list.get(i)[0] + " " + list.get(i)[1]);
                }
            }
        }
    }
}


为什么难度是较难😀
发表于 2024-03-25 18:42:47 回复(0)
//stream流真的很爽,注意名字可能重复,传一个数组进去就可以避免这个问题
import java.util.*;
public class Main {
    private static Map<String[],Integer> map = new LinkedHashMap<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int num = Integer.parseInt(sc.nextLine());
         int index = Integer.parseInt(sc.nextLine());
        for(int i = 0; i < num; i++){
            String[] strs = sc.nextLine().split(" ");
            map.put(strs, Integer.parseInt(strs[1]));
        }
        map.entrySet().stream().sorted((o1, o2) -> {
            if(index == 0){
                return o2.getValue() - o1.getValue();
            }else{
                return o1.getValue() - o2.getValue();
            }
        }).forEach(o1 -> System.out.println(o1.getKey()[0] + " " + o1.getValue()));
    }
}
编辑于 2024-03-22 19:20:46 回复(0)
道理我都懂,但这题目说,“相同成绩都按先录入排列在前的规则处理”
编辑于 2024-03-22 15:44:57 回复(0)