这个问题要求我们书写几个函数: 1) 输入10个职工的姓名和职工号; 2) 按职工号从小到大排序,姓名也相应改变顺序; 3) 要求输入一个职工号,用折半法找出该职工的姓名,从主函数输入要查找的职工的职工号,输出该职工的姓名。C语言
时间: 2024-04-09 21:29:06 浏览: 20
下面是一个实现以上要求的示例代码:
```c
#include <stdio.h>
#include <string.h>
struct Employee {
char name[50];
int id;
};
void inputEmployees(struct Employee employees[], int n) {
printf("Enter the names and IDs of 10 employees:\n");
for (int i = 0; i < n; i++) {
printf("Employee %d:\n", i + 1);
printf("Name: ");
scanf("%s", employees[i].name);
printf("ID: ");
scanf("%d", &employees[i].id);
}
}
void sortEmployees(struct Employee employees[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (employees[j].id > employees[j + 1].id) {
// 交换职工号
int tempId = employees[j].id;
employees[j].id = employees[j + 1].id;
employees[j + 1].id = tempId;
// 交换姓名
char tempName[50];
strcpy(tempName, employees[j].name);
strcpy(employees[j].name, employees[j + 1].name);
strcpy(employees[j + 1].name, tempName);
}
}
}
}
int binarySearch(struct Employee employees[], int n, int targetId) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (employees[mid].id == targetId) {
return mid; // 找到目标职工号的索引
} else if (employees[mid].id < targetId) {
low = mid + 1; // 目标在右侧
} else {
high = mid - 1; // 目标在左侧
}
}
return -1; // 没找到目标职工号
}
int main() {
struct Employee employees[10];
int targetId, targetIndex;
inputEmployees(employees, 10);
sortEmployees(employees, 10);
printf("\nEnter the ID of the employee to search: ");
scanf("%d", &targetId);
targetIndex = binarySearch(employees, 10, targetId);
if (targetIndex != -1) {
printf("Employee found!\n");
printf("Name: %s\n", employees[targetIndex].name);
} else {
printf("Employee not found!\n");
}
return 0;
}
```
这段代码首先定义了一个结构体 `Employee`,包含了职工的姓名和职工号。然后通过 `inputEmployees` 函数输入10个职工的姓名和职工号,通过 `sortEmployees` 函数按职工号从小到大排序。最后,通过 `binarySearch` 函数使用折半法查找指定职工号的姓名,并在主函数中进行输出。