每日一题——第八十四题

题目:编写函数

1、输入10个职工的姓名和职工号
2、按照职工由大到小顺序排列,姓名顺序也随之调整
3、要求输入一个职工号,用折半查找法找出该职工的姓名

#define  _CRT_SECURE_NO_WARNINGS
#include
#include
#define MAX_EMPLOYEES 10

typedef struct {
	int id;
	char name[50];
}Empolyee;

void  inputEmployees(Empolyee employees[], int n);
void sortEmpolyee(Empolyee employees[], int n);
int binarySearch(Empolyee employees[], int n, int id);

int main() {
	Empolyee employees[MAX_EMPLOYEES];

	//输入员工的信息
	inputEmployees(employees, MAX_EMPLOYEES);

	//排序员工信息
	sortEmpolyee(employees, MAX_EMPLOYEES);

	//打印排序后的职工信息
	printf("排序后的职工信息:\n");

	for (int i = 0; i < MAX_EMPLOYEES; i++)
	{
		printf("ID : %d,  姓名:  %s\n", employees[i].id, employees[i].name);
	}
	//查找员工
	int searchId;
	printf("请输入要查找的ID:");
	scanf_s("%d", &searchId);

	int index = binarySearch(employees, MAX_EMPLOYEES, searchId);
	if (index != -1) {
		printf("找到:ID %d, 姓名: %s\n", employees[index].id, employees[index].name);
	}
	else
	{
		printf("未找到ID为%d的职工\n", searchId);
	}
	return 0;
}

void  inputEmployees(Empolyee employees[], int n) {
	for (int i = 0; i < n; i++) {
		printf("请输入第%d位员工的ID和姓名: ", i + 1);
		scanf("%d %s", &employees[i].id, employees[i].name);
	}
}

/// 
/// 按照职工号ID,从小到大排列员工
/// 
/// 
/// 
void sortEmpolyee(Empolyee 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) {

				Empolyee tmp = employees[j];
				employees[j] = employees[j + 1];
				employees[j + 1] = tmp;
			}
		}
	}
}


/// 
/// 折半查找求职工的姓名
/// 
/// 
/// 
/// 
/// 
int binarySearch(Empolyee employees[], int n, int id) {

	int low = 0, high = n - 1;

	while (low <= high) {
		int mid = low + (high - low) / 2;//注意这里是上取整
		if (employees[mid].id == id) {
			return mid;//找到职工号,返回索引
		}
		else if (employees[mid].id < id) {
			low = mid + 1;
		}
		else
		{
			high = mid - 1;
		}
	}
	return -1;
}

你可能感兴趣的:(C语言程序设计每日一练,c语言)