c++代码用结构体写倒置排序
时间: 2023-03-25 13:00:57 浏览: 92
下面是用结构体写的倒置排序的 C 代码:
```c
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
void swap(struct Student *a, struct Student *b) {
struct Student temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(struct Student arr[], int n) {
int i, j;
for (i = ; i < n-1; i++) {
for (j = ; j < n-i-1; j++) {
if (arr[j].score < arr[j+1].score) {
swap(&arr[j], &arr[j+1]);
}
}
}
}
int main() {
struct Student students[5] = {
{"Tom", 80},
{"Jerry", 90},
{"Alice", 70},
{"Bob", 85},
{"David", 75}
};
int i;
printf("排序前:\n");
for (i = ; i < 5; i++) {
printf("%s %d\n", students[i].name, students[i].score);
}
bubbleSort(students, 5);
printf("排序后:\n");
for (i = ; i < 5; i++) {
printf("%s %d\n", students[i].name, students[i].score);
}
return ;
}
```
这个程序定义了一个结构体 `Student`,包含学生的姓名和成绩。然后定义了两个函数 `swap` 和 `bubbleSort`,分别用于交换两个结构体变量的值和对结构体数组进行冒泡排序。最后在 `main` 函数中创建了一个包含 5 个学生信息的结构体数组,先输出排序前的结果,再调用 `bubbleSort` 函数进行排序,最后输出排序后的结果。