实现按照工资卡号升序、实发工资降序以及姓名字典序排序c
时间: 2023-12-24 07:05:08 浏览: 86
c++实现的字典排序
下面是一个示例代码,实现了按照工资卡号升序、实发工资降序、姓名字典序排序的功能:
```c
#include <stdio.h>
#include <string.h>
#define MAX_EMPLOYEES 100
struct Employee {
char name[50];
int salaryCardNum;
double netSalary;
};
int compareByCardNum(const void* a, const void* b) {
const struct Employee* emp1 = (const struct Employee*)a;
const struct Employee* emp2 = (const struct Employee*)b;
return emp1->salaryCardNum - emp2->salaryCardNum;
}
int compareByNetSalary(const void* a, const void* b) {
const struct Employee* emp1 = (const struct Employee*)a;
const struct Employee* emp2 = (const struct Employee*)b;
if (emp1->netSalary < emp2->netSalary) {
return 1;
} else if (emp1->netSalary > emp2->netSalary) {
return -1;
} else {
return 0;
}
}
int compareByName(const void* a, const void* b) {
const struct Employee* emp1 = (const struct Employee*)a;
const struct Employee* emp2 = (const struct Employee*)b;
return strcmp(emp1->name, emp2->name);
}
int main() {
struct Employee employees[MAX_EMPLOYEES];
int numEmployees;
// 从键盘输入员工信息
printf("请输入员工个数:");
scanf("%d", &numEmployees);
for (int i = 0; i < numEmployees; i++) {
printf("请输入第%d个员工信息(姓名 工资卡号 实发工资):", i+1);
scanf("%s %d %lf", employees[i].name, &employees[i].salaryCardNum, &employees[i].netSalary);
}
// 按照工资卡号升序排序
qsort(employees, numEmployees, sizeof(struct Employee), compareByCardNum);
// 找到相邻实发工资相同的员工区间,对每个区间按照姓名字典序排序
int start = 0;
for (int i = 1; i <= numEmployees; i++) {
if (i == numEmployees || employees[i].netSalary != employees[start].netSalary) {
qsort(&employees[start], i-start, sizeof(struct Employee), compareByName);
start = i;
}
}
// 按照实发工资降序排序
qsort(employees, numEmployees, sizeof(struct Employee), compareByNetSalary);
// 输出排序后的结果
printf("排序后的结果为:\n");
for (int i = 0; i < numEmployees; i++) {
printf("%s %d %.2lf\n", employees[i].name, employees[i].salaryCardNum, employees[i].netSalary);
}
return 0;
}
```
这个程序使用了 C 标准库中的 `qsort` 函数来进行快速排序,同时定义了三个比较函数,分别用于按照工资卡号升序、实发工资降序、姓名字典序排序。在程序中,先按照工资卡号升序排序,然后找到相邻实发工资相同的员工区间,对每个区间按照姓名字典序排序,最后按照实发工资降序排序。
阅读全文