结构体数组的应用

写几个函数:

①输入10个职工的姓名和职工号;

②按职工号由小到大顺序排列,姓名顺序也随之调整;

③要求输入一个职工号,用折半查找找出该职工的姓名,从主函数输入要查找的职工号,输出该职工姓名。

#include 
#include 
#define MAX_EMPLOYEES 10
struct Employee 
{
    char name[50];
    int emp_id;
};
void inputEmployeeInfo(struct Employee employees[MAX_EMPLOYEES])
{
    for (int i = 0; i < MAX_EMPLOYEES; ++i)
    {
        printf("请输入第%d个职工的姓名:", i + 1);
        scanf("%s", employees[i].name);
        printf("请输入第%d个职工的职工号:", i + 1);
        scanf("%d", &employees[i].emp_id);
    }
}
void sortEmployees(struct Employee employees[MAX_EMPLOYEES])
{
    struct Employee temp;
    for (int i = 0; i < MAX_EMPLOYEES - 1; ++i)
    {
        for (int j = 0; j < MAX_EMPLOYEES - i - 1; ++j)
        {
            if (employees[j].emp_id > employees[j + 1].emp_id)
            {
                // 交换职工号和姓名
                temp = employees[j];
                employees[j] = employees[j + 1];
                employees[j + 1] = temp;
            }
        }
    }
    // 打印排序后的名字和职工号
    printf("\n排序后的名字和职工号:\n");
    for (int i = 0; i < MAX_EMPLOYEES; ++i)
    {
        printf("姓名:%s, 职工号:%d\n", employees[i].name, employees[i].emp_id);
    }
}
char* binarySearch(struct Employee employees[MAX_EMPLOYEES], int targetEmpId) 
{
    int low = 0, high = MAX_EMPLOYEES - 1, mid;

    while (low <= high) 
    {
        mid = (low + high) / 2;
        if (employees[mid].emp_id == targetEmpId)
        {
            return employees[mid].name;
        }
        else if (employees[mid].emp_id < targetEmpId) 
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return NULL;
}
int main()
{
    struct Employee employees[MAX_EMPLOYEES];
    int targetEmpId;

    // 输入职工信息
    inputEmployeeInfo(employees);

    // 按职工号排序
    sortEmployees(employees);

    // 输入要查找的职工号
    printf("\n请输入要查找的职工号:");
    scanf("%d", &targetEmpId);

    // 折半查找并输出结果
    char* resultName = binarySearch(employees, targetEmpId);
    if (resultName != NULL) {
        printf("职工号为%d的职工姓名是:%s\n", targetEmpId, resultName);
    }
    else 
    {
        printf("未找到职工号为%d的职工信息。\n", targetEmpId);
    }
    return 0;
}

你可能感兴趣的:(算法)