C语言输入1.十个职工的姓名和职工号 2.按照职工号由大到小顺序排序,姓名顺序也随之调整; 3.要求输入一个职工号,用折半查找法找出该职工的姓名,从主函数输入要查找的职工号,输出该职工姓名
时间: 2024-05-13 08:15:55 浏览: 65
下面是一个可能的解决方案:
```c
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_EMPLOYEE_NUM 10
struct Employee {
char name[MAX_NAME_LEN];
int id;
};
void sort_employees(struct Employee employees[], int n);
int binary_search(const struct Employee employees[], int n, int target_id);
int main() {
struct Employee employees[MAX_EMPLOYEE_NUM];
int i, n, target_id, index;
printf("请输入%d个职工的姓名和职工号:\n", MAX_EMPLOYEE_NUM);
for (i = 0; i < MAX_EMPLOYEE_NUM; i++) {
printf("职工%d的姓名:", i + 1);
scanf("%s", employees[i].name);
printf("职工%d的职工号:", i + 1);
scanf("%d", &employees[i].id);
}
sort_employees(employees, MAX_EMPLOYEE_NUM);
printf("\n按照职工号排序的结果:\n");
for (i = 0; i < MAX_EMPLOYEE_NUM; i++) {
printf("%d\t%s\n", employees[i].id, employees[i].name);
}
printf("\n请输入要查找的职工号:");
scanf("%d", &target_id);
index = binary_search(employees, MAX_EMPLOYEE_NUM, target_id);
if (index == -1) {
printf("没有找到职工号为%d的职工\n", target_id);
} else {
printf("职工号为%d的职工是:%s\n", target_id, employees[index].name);
}
return 0;
}
void sort_employees(struct Employee employees[], int n) {
int i, j;
struct Employee temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (employees[i].id < employees[j].id) {
temp = employees[i];
employees[i] = employees[j];
employees[j] = temp;
}
}
}
}
int binary_search(const struct Employee employees[], int n, int target_id) {
int low = 0, high = n - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (employees[mid].id == target_id) {
return mid;
} else if (employees[mid].id < target_id) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
```
这个程序定义了一个 `Employee` 结构体,其中包含职工的姓名和职工号。首先用户需要输入十个职工的姓名和职工号,然后程序会按照职工号从大到小排序并输出结果。最后用户可以输入要查找的职工号,程序会使用折半查找法在已排序的员工数组中查找该职工号,并输出该职工的姓名。
阅读全文