题目

定义学生结构体 Student(包含姓名与成绩),读入 n 名学生的数据,调用 qsort 按成绩从高到低降序排序,并依次输出学生姓名与成绩。

输入格式:第一行输入学生人数 n;随后 n 行每行输入学生姓名(无空格)和整数成绩。

输出格式:按成绩降序分行输出排序后的学生姓名与成绩。

数据范围与约定:1 ≤ n ≤ 100,成绩为整数。

思路与算法

1. 结构体数组模型
声明 struct Student list[100]; 管理批量记录。

2. qsort 结构体比较函数
比较函数参数转换为结构体指针 const struct Student *s1 = (const struct Student *)a;。降序排序返回 s2->score - s1->score。

完整程序

import java.util.Arrays;
import java.util.Scanner;

class Student implements Comparable<Student> {
    String name;
    int score;

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

    // 按成绩降序排列
    @Override
    public int compareTo(Student o) {
        return Integer.compare(o.score, this.score);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        if (!sc.hasNextInt()) return;
        int n = sc.nextInt();
        Student[] list = new Student[n];

        for (int i = 0; i < n; i++) {
            String name = sc.next();
            int score = sc.nextInt();
            list[i] = new Student(name, score);
        }

        Arrays.sort(list);

        for (Student s : list) {
            System.out.println(s.name);
        }
    }
}

运行示例

输入:

Amy 85
Bob 92
Cal 78

输出:

Bob
Amy
Cal