* 函数名称:sort * 函数功能:对教师数组元素按工资由小到大进行排序 * 形式参数:t, struct teacher型指针,教师数组首地址 * 形式参数:n, int型,教师数组元素个数
时间: 2024-05-01 18:21:03 浏览: 123
下面是一个对教师数组按照工资由小到大排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
int age;
float salary;
} teacher;
void sort(teacher *t, int n) {
int i, j;
teacher temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (t[i].salary > t[j].salary) {
temp = t[i];
t[i] = t[j];
t[j] = temp;
}
}
}
}
int main() {
teacher t[5] = {
{"Tom", 30, 2500},
{"Jerry", 25, 3000},
{"Alice", 35, 2000},
{"Bob", 28, 3500},
{"Lucy", 33, 1800}
};
int i;
printf("Before sorting:\n");
for (i = 0; i < 5; i++) {
printf("%s\t%d\t%.2f\n", t[i].name, t[i].age, t[i].salary);
}
sort(t, 5);
printf("After sorting:\n");
for (i = 0; i < 5; i++) {
printf("%s\t%d\t%.2f\n", t[i].name, t[i].age, t[i].salary);
}
return 0;
}
```
输出结果为:
```
Before sorting:
Tom 30 2500.00
Jerry 25 3000.00
Alice 35 2000.00
Bob 28 3500.00
Lucy 33 1800.00
After sorting:
Lucy 33 1800.00
Alice 35 2000.00
Tom 30 2500.00
Jerry 25 3000.00
Bob 28 3500.00
```
阅读全文