BUPT-homework/semester1/pset14/2-3-StructSort.c

68 lines
1.4 KiB
C
Raw Permalink Normal View History

2021-12-16 17:27:53 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma GCC optimize("Ofast,inline")
#define MAX 21
typedef struct STUDENT {
char name[MAX];
int score;
} STUDENT;
void GetInput(STUDENT **dude);
void sort(STUDENT *students, int n);
void PrintStudent(STUDENT dude);
void swap(STUDENT *left, STUDENT *right);
int main(void) {
int n;
scanf("%d", &n);
STUDENT students[n];
for (int i = 0; i < n; i++) {
scanf("%s", students[i].name);
scanf("%d", &(students[i].score));
}
sort(students, n);
for (int i = 0; i < n; i++) {
printf("Name:%s\n", students[i].name);
printf("total:%d\n", students[i].score);
printf("\n");
}
return 0;
}
void sort(STUDENT *students, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (students[j].score < students[j + 1].score) {
swap(&students[j], &students[j + 1]);
} else if (students[j].score == students[j + 1].score) {
if (strcmp(students[j].name, students[j + 1].name) > 0) {
swap(&students[j], &students[j + 1]);
}
}
}
}
}
void PrintStudent(STUDENT dude) {
printf("Name:%s\n", dude.name);
printf("total:%d\n", dude.score);
}
void swap(STUDENT *left, STUDENT *right) {
STUDENT tmp;
// Swap name
strcpy(tmp.name, left->name);
strcpy(left->name, right->name);
strcpy(right->name, tmp.name);
// Swap score
int temp = left->score;
left->score = right->score;
right->score = temp;
}