题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/3f27a0a5a59643a8abf0140b9a8cf1f7
注意!虽然冒泡排序是稳定的算法,但是测试用例不是全都按照学号由小到大的顺序输入的,所以一定要对成绩相同的学生进行学号的排序。
#include <algorithm> #include <iostream> using namespace std; struct student{ int num; int score; }; void Mysort(struct student std[], int n){ //冒泡排序 for (int i = 0; i < n-1; i++){ for (int j = n-1; j > i; j--){ if (std[j].score < std[j-1].score){ struct student temp = std[j]; std[j] = std[j-1]; std[j-1] = temp; } else if (std[j].score == std[j-1].score && std[j].num < std[j-1].num){ struct student temp = std[j]; std[j] = std[j-1]; std[j-1] = temp; } } } //成绩相同,则按照学号的大小进行从小到大排序 } int main() { int n; while (cin >> n) { // 注意 while 处理多个 case struct student stu[n]; for (int i = 0; i < n; i++){ cin >> stu[i].num >> stu[i].score; } Mysort(stu, n); for (int i = 0; i < n; i++){ cout << stu[i].num << " " << stu[i].score << endl; } } } // 64 位输出请用 printf("%lld")