#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义员工结构体
struct Employee {
char name[30];
int id;
struct {
char department[30];
float salary;
} details;
};
// 交换两个员工信息
void swap(struct Employee *a, struct Employee *b) {
struct Employee temp = *a;
*a = *b;
*b = temp;
}
// 快速排序分区函数
int partition(struct Employee arr[], int low, int high) {
int pivot = arr[high].id;
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j].id < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// 快速排序函数
void quickSort(struct Employee arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
struct Employee *employees = (struct Employee *)malloc(100 * sizeof(struct Employee));
if (employees == NULL) {
printf("内存分配失败\n");
return 1;
}
FILE *file = fopen("employees.txt", "r");
if (file == NULL) {
printf("文件打开失败\n");
free(employees);
return 1;
}
int count = 0;
while (fscanf(file, "%29s %d %29s %f", employees[count].name, &employees[count].id, employees[count].details.department, &employees[count].details.salary) != EOF && count < 100) {
count++;
}
fclose(file);
quickSort(employees, 0, count - 1);
// 输出排序后的员工信息
for (int i = 0; i < count; i++) {
printf("Name: %s, ID: %d, Department: %s, Salary: %.2f\n", employees[i].name, employees[i].id, employees[i].details.department, employees[i].details.salary);
}
free(employees);
return 0;
}
- 结构体定义:定义了
struct Employee
结构体来表示员工信息,包含姓名、编号、部门和薪资信息。
- 内存分配:使用
malloc
动态分配内存,创建可容纳100个员工信息的结构体数组。
- 文件读取:从文件中读取员工信息,填充到结构体数组中。
- 快速排序:实现了快速排序算法,根据员工编号对结构体数组进行排序。
- 输出排序结果:在主函数中调用快速排序函数,并输出排序后的员工信息。
- 内存释放:使用
free
释放动态分配的内存。