写几个函数 输入十个职工的姓名和职工号 按职工号由小到大排序,姓名顺序也随之调整 要求输入一个职工号,用折半查找法找出该职工的姓名,从主函数输入要查找的职工号,输出该职工的姓名并写出其主函数 C语言
时间: 2024-06-13 17:10:08 浏览: 31
以下是C语言的代码实现,包括输入十个职工的姓名和职工号、按职工号由小到大排序,姓名顺序也随之调整、折半查找法找出该职工的姓名并输出的功能:
```c
#include <stdio.h>
#include <string.h>
#define MAX_NUM 10
struct Employee {
char name[20];
int id;
};
void sort(struct Employee *employees, int n);
int binarySearch(struct Employee *employees, int n, int id);
void printEmployee(struct Employee employee);
int main() {
struct Employee employees[MAX_NUM];
int i, id, index;
// 输入十个职工的姓名和职工号
printf("请输入十个职工的姓名和职工号:\n");
for (i = 0; i < MAX_NUM; i++) {
printf("请输入第%d个职工的姓名:", i + 1);
scanf("%s", employees[i].name);
printf("请输入第%d个职工的职工号:", i + 1);
scanf("%d", &employees[i].id);
}
// 按职工号由小到大排序,姓名顺序也随之调整
sort(employees, MAX_NUM);
// 要求输入一个职工号,用折半查找法找出该职工的姓名
printf("请输入要查找的职工号:");
scanf("%d", &id);
index = binarySearch(employees, MAX_NUM, id);
// 输出该职工姓名
if (index == -1) {
printf("未找到该职工!\n");
} else {
printf("该职工姓名为:");
printEmployee(employees[index]);
}
return 0;
}
// 按职工号由小到大排序,姓名顺序也随之调整
void sort(struct Employee *employees, int n) {
int i, j;
struct Employee temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (employees[j].id > employees[j + 1].id) {
temp = employees[j];
employees[j] = employees[j + 1];
employees[j + 1] = temp;
}
}
}
}
// 折半查找法找出该职工的姓名
int binarySearch(struct Employee *employees, int n, int id) {
int left = 0, right = n - 1, mid;
while (left <= right) {
mid = (left + right) / 2;
if (employees[mid].id == id) {
return mid;
} else if (employees[mid].id > id) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
// 输出职工信息
void printEmployee(struct Employee employee) {
printf("%s\n", employee.name);
}
```