首页 > 试题广场 >

成绩排序

[编程题]成绩排序
  • 热度指数:208291 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一些同学的信息(名字,成绩)序列,请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩

都按先录入排列在前的规则处理。

例示:
jack      70
peter     96
Tom       70
smith     67

从高到低  成绩
peter     96
jack      70
Tom       70
smith     67

从低到高

smith     67

jack      70

Tom       70
peter     96

注:0代表从高到低,1代表从低到高

数据范围:人数:
进阶:时间复杂度:,空间复杂度:

输入描述:

第一行输入要排序的人的个数n,第二行输入一个整数表示排序的方式,之后n行分别输入他们的名字和成绩,以一个空格隔开



输出描述:

按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开

示例1

输入

3
0
fang 90
yang 50
ning 70

输出

fang 90
ning 70
yang 50
示例2

输入

3
1
fang 90
yang 50
ning 70

输出

yang 50
ning 70
fang 90
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)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    static class Item {
        public String name;
        public Integer score;
        public Integer index;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(), s = in.nextInt();
        List<Item> list = new ArrayList();
        int c = 0;
        while (n -- > 0) {
            Item item = new Item();
            item.index = ++ c;
            item.name = in.next();
            item.score = in.nextInt();
            list.add(item);
        }
        Collections.sort(list, (r1, r2) -> {
            if (r1.score == r2.score) return r1.index.compareTo(r2.index);
            return s == 1 ? r1.score.compareTo(r2.score) : r2.score.compareTo(r1.score);
        });
        list.forEach(item -> System.out.println(item.name + " " + item.score));
    }
}

编辑于 2024-03-16 19:22:26 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = in.nextInt();
        int asc = in.nextInt();
        in.nextLine();
        String[] names = new String[count];
        int[] scores = new int[count];
        int[] ordered = new int[count];
        for(int i=0;i<count;i++){
            String[] arr = in.nextLine().split("\\s+");
            names[i] = arr[0];
            scores[i] = Integer.parseInt(arr[1]);
            ordered[i] = i;
        }

        for(int i=0;i<count;i++){
            for(int j=i+1;j<count;j++){
                if((scores[i] == scores[j] && ordered[i] > ordered[j])
                    || (asc == 0 && scores[i] < scores[j])
                    || (asc == 1 && scores[i] > scores[j])
                ){
                    scores[i]  = scores[i]+scores[j]-(scores[j]=scores[i]);
                    ordered[i]  = ordered[i]+ordered[j]-(ordered[j]=ordered[i]);
                }
            }
        }

        for(int i=0;i<count;i++){
            System.out.println(names[ordered[i]]+" "+scores[i]);
        }
    }
}

编辑于 2024-03-15 11:38:20 回复(0)
import java.util.*; 
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); 
        int n = scanner.nextInt(); // 读取人数  
        int order = scanner.nextInt(); // 读取排序方式,0代表从高到低,1代表从低到高   
        // 使用HashMap存储学生信息,确保相同成绩时,先录入的排在前面  
        List<Map<String, Object>> students = new ArrayList<>(); 
        for (int i = 0; i < n; i++) {  
            Map<String, Object> map = new HashMap<>();
            String name = scanner.next(); 
            int score = scanner.nextInt();
            map.put("score",score);
            map.put("name",name);
            students.add(map); 
    }   
    // 使用TreeMap根据成绩排序  
    Map<Integer, List<String>> sortedStudents = new TreeMap<Integer, List<String>>(order == 0 ? Comparator.reverseOrder() : Comparator.naturalOrder());
        for (Map<String, Object> student : students) {  
            sortedStudents.computeIfAbsent(Integer.parseInt(student.get("score").toString()),
                k -> new ArrayList<>()).add(student.get("name").toString()); 
        }   
        // 输出结果  
        for (Map.Entry<Integer, List<String>> entry : sortedStudents.entrySet()) {  
            int score = entry.getKey();
            List<String> names = entry.getValue(); 
            for (int i = 0; i < names.size(); i++) {  
                System.out.println(names.get(i) + " " + score); 
            }  }  scanner.close(); 
    }

编辑于 2024-02-03 12:30:42 回复(0)
import java.util.ArrayList;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String l1 = in.nextLine();
        String l2 = in.nextLine();
        ArrayList<String> list = new ArrayList<String>();
        while (in.hasNextLine()) {
            list.add(in.nextLine());
        }
        in.close();

        list.stream().sorted((o1, o2)-> {
            String o1Score = o1.substring(o1.indexOf(" ") + 1);
            String o2Score = o2.substring(o2.indexOf(" ") + 1);
            return Integer.compare(Integer.valueOf(o1Score), Integer.valueOf(o2Score)) * (l2.equals("1") ? 1 : -1);
        }).forEach(item->System.out.println(item));
    }
}


发表于 2024-01-11 15:03:39 回复(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 sortNum = in.nextInt();
        // List<User> list = new ArrayList();
        User[] users = new User[n];
        User[] temp = new User[n];
        for (int i = 0; i < n; i++) {
            String username = in.next();
            int grade = in.nextInt();
            users[i] = new User(username, grade);
        }
        mergeSort(users, 0, n-1, temp, sortNum);
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
    public static void mergeSort(User[] users, int left, int right, User[] temp, int sortNum) {
        if (left < right) {
            int mid = (left + right) >> 1;
            mergeSort(users, left, mid, temp, sortNum);
            mergeSort(users, mid+1, right, temp, sortNum);
            merge(users, left, mid, right, temp, sortNum);
        }
    }
    public static void merge(User[] users, int left, int mid, int right, User[] temp, int sortNum) {
        int i = left, j = mid + 1, k = left;
        while (i <= mid && j <= right) {
            // 这里的小于等于/大于实现了稳定性
            if (sortNum == 1) {
                if (users[i].grade <= users[j].grade) {
                    temp[k++] = users[i++];
                } else {
                    temp[k++] = users[j++];
                }
            } else {
                if (users[i].grade >= users[j].grade) {
                    temp[k++] = users[i++];
                } else {
                    temp[k++] = users[j++];
                }                
            }

        }
        while (i <= mid) temp[k++] = users[i++];
        while (j <= right) temp[k++] = users[j++];
        k = left;
        while (k <= right) users[k] = temp[k++];
    }
}
class User {
    public String username;
    public int grade;
    public User (String username, int grade) {
        this.username = username;
        this.grade = grade;
    }
    public String toString() {
        return this.username+" "+this.grade;
    }
}

编辑于 2023-12-09 00:31:09 回复(0)
import java.util.*;

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

        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        int count = in.nextInt();
        int sortType = in.nextInt();
        while (count > 0) {
            String name = in.next();
            String score = in.next();
            HashMap<String, String> map = new HashMap<>();
            map.put("name", name);
            map.put("score", score);
            list.add(map);
            count--;
        }

        list.sort((m1, m2) -> {
            Integer score1 = Integer.valueOf(m1.get("score"));
            Integer score2 = Integer.valueOf(m2.get("score"));
            if (score1 - score2 != 0) {
                return sortType == 0 ? score2 - score1 : score1 - score2;
            } else {
                return 0;
            }
        });

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

编辑于 2023-12-04 17:58:45 回复(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 k = in.nextInt();
        in.nextLine();
        List<Record> list = new ArrayList();
        for(int i = 0; i < n; i++){
            String [] s = in.nextLine().split(" ");
            list.add(new Record(s[0], Integer.parseInt(s[1])));
        }
        Collections.sort(list, (o1, o2)-> k == 0 ? o2.score - o1.score : o1.score - o2.score);
        list.forEach(( e -> System.out.println(e.name + " "+ e.score)));
    }
}

class Record{
    String name;
    Integer score;
    public Record(String name, Integer score){
        this.name = name;
        this.score = score;
    }
}

发表于 2023-11-26 16:49:21 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int num = in.nextInt();
            Boolean isAscending = false;
            if (in.nextInt() > 0) {
                isAscending = true;
            }
            List<student> list=new ArrayList<>();
            for (int i = 0; i < num; i++) {
                list.add(new student(i,in.next(),in.nextInt()));
            }
            list=sort(list,isAscending);

            for (student student:list
            ) {
                System.out.println(student.name + " " + student.score);
            }
        }
    }

    public static List<student> sort(List<student> list, Boolean isAscending) {
        List<student> sortedlist=list;
        Collections.sort(sortedlist, new Comparator<student>() {
            @Override
            public int compare(student s1, student s2) {
                if (s1.score==s2.score)
                {return 0;}
                else if (isAscending) {
                    return s1.score - s2.score;
                } else {
                    return s2.score - s1.score;
                }
            }
        });
        return sortedlist;
    }
    static class student{
       public int num;
       public int score;
       public String name;

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

发表于 2023-09-07 20:14:11 回复(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 a = Integer.parseInt(in.nextLine());
            int direction = Integer.parseInt(in.nextLine());
            String[] ss = new String[a];
            for(int i = 0; i < a; i ++) {
                ss[i] = in.nextLine();
            }
            TreeMap<Integer, ArrayList<String>> map = new TreeMap<>();
            for(String s:ss) {
                String[] scs = s.split(" ");
                String name = scs[0];
                int score = Integer.parseInt(scs[1]);
                ArrayList<String> list = map.getOrDefault(score,new ArrayList<>());
                list.add(name);
                map.put(score,list);
            }
            NavigableSet<Integer> set =  map.navigableKeySet();
            Integer[] keys = set.toArray(new Integer[0]);
            if(direction == 1)
            for(Integer score: keys) {
                ArrayList<String> list = map.get(score);
                for(String name: list) {
                    System.out.println(name + " " + score);
                }
            }
            else
                for(int i = keys.length-1; i >= 0; i --) {
                    int score = keys[i];
                    ArrayList<String> list = map.get(score);
                    for(String name: list) {
                        System.out.println(name + " " + score);
                    }
                }
        }
    }
}

发表于 2023-09-03 23:04:36 回复(0)
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 num = Integer.parseInt(br.readLine());
        // 排序标志 0降序 1升序
        String sortFlag = br.readLine();
        String[][] arrTwo = new String[num][2];
        for (int i = 0; i < num; i++) {
            String[] split = br.readLine().split(" ");
            arrTwo[i] = split;
        }
        Arrays.sort(arrTwo, (o1, o2) -> {
            int i1 = Integer.parseInt(o1[1]);
            int i2 = Integer.parseInt(o2[1]);
            if ("0".equals(sortFlag)) {
                // 如果是降序
                return i2 - i1;
            } else {
                return i1 - i2;
            }
        });
        StringBuilder stringBuilder = new StringBuilder();
        for (String[] arr : arrTwo) {
            stringBuilder.append(arr[0]).append(" ").append(arr[1]).append("\n");
        }
        System.out.println(stringBuilder);
    }

}
使用二维数组
发表于 2023-08-09 23:22:19 回复(0)
 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int sort = in.nextInt();
        LinkedHashMap<Integer, Integer> mapScore = new LinkedHashMap<>();
        LinkedHashMap<Integer, String> mapName = new LinkedHashMap<>();
        for (int i =0;i<n;i++){
            mapName.put(i,in.next());
            mapScore.put(i,in.nextInt());
        }
        ArrayList<Map.Entry<Integer,Integer>> list = new ArrayList<>(mapScore.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                if (sort==1){
                    return o1.getValue()-o2.getValue();
                }else {
                    return o2.getValue()-o1.getValue();
                }
                }
            });
        mapScore.clear();
        for (Map.Entry<Integer,Integer> entry:list){
            mapScore.put(entry.getKey(), entry.getValue());
        }
        Set<Integer> set = mapScore.keySet();
        for (int key : set){
            System.out.println(mapName.get(key)+" "+mapScore.get(key));
        }
    }

发表于 2023-07-21 18:21:38 回复(0)