• 写几个函数: ①输人10个职工的姓名和职工号; ②按职工号由小到大顺序排序,姓名顺序也随之调整; ③要求输人一个职工号,用折半查找法找出该职工的姓名,从主函数输人要查找的职工号,输出该职工姓名


    写几个函数:①输人10个职工的姓名和职工号;②按职工号由小到大顺序排序,姓名顺序也随之调整;③要求输人一个职工号,用折半查找法找出该职工的姓名,从主函数输人要查找的职工号,输出该职工姓名。

    题目解析:

    利用二分查找的关键在于数据一定要先有序,所以在查找前我们需要对数据进行排序。

    代码示例:

    #include<stdio.h>
    
    #define N 10
    
    void input(int num[], char name[N][8])
    {
    	int i;
    	for (i = 0; i < N; i++)
    	{
    		printf("input NO.: ");
    		scanf("%d", &num[i]);
    		printf("input name: ");
    		getchar();
    		gets(name[i]);
    	}
    }
    
    void sort(int num[], char name[N][8])
    {
    	int i, j, min, templ;
    	char temp2[8];
    	for (i = 0; i < N - 1; i++)
    	{
    		min = i;
    		for (j = i; j<N; j++)
    		if (num[min]>num[j])  min = j;
    		templ = num[i];
    		strcpy(temp2, name[i]);
    		num[i] = num[min];
    		strcpy(name[i], name[min]);
    		num[min] = templ;
    		strcpy(name[min], temp2);
    	}
    	printf("
     result:
    ");
    	for (i = 0; i < N; i++)
    		printf("
     %5d%10s", num[i], name[i]);
    }
    
    void search(int n, int num[], char name[N][8])
    {
    	int top, bott, mid, loca, sign;
    	top = 0;
    	bott = N - 1;
    	loca = 0;
    	sign = 1;
    	if ((n<num[0]) || (n>num[N - 1]))
    		loca = -1;
    	while ((sign == 1) && (top <= bott))
    	{
    		mid = (bott + top) / 2;
    		if (n == num[mid])
    		{
    			loca = mid;
    			printf("NO. %d , his name is %s.
    ", n, name[loca]);
    			sign = -1;
    		}
    		else if (n < num[mid])
    			bott = mid - 1;
    		else
    			top = mid + 1;
    	}
    	if (sign == 1 || loca == -1)
    		printf("%d not been found.
    ", n);
    }
    
    int main()
    {
    	int num[N], number, flag = 1, c;
    	char name[N][8];
    
    	input(num, name);
    	sort(num, name);
    
    	while (flag == 1)
    	{
    		printf("
    input number to look for:");
    		scanf("%d", &number);
    		search(number, num, name);
    		printf("continue ot not(Y/N)?");
    		getchar();
    		c = getchar();
    		if (c == 'N' || c == 'n')
    			flag = 0;
    	}
    	return 0;
    }
    

    运行结果:

    写几个函数:  ①输人10个职工的姓名和职工号; ②按职工号由小到大顺序排序,姓名顺序也随之调整;
    ③要求输人一个职工号,用折半查找法找出该职工的姓名,从主函数输人要查找的职工号,输出该职工姓名

  • 相关阅读:
    【bzoj4591】[Shoi2015]超能粒子炮·改 Lucas定理
    【bzoj1604】[Usaco2008 Open]Cow Neighborhoods 奶牛的邻居 旋转坐标系+并查集+Treap/STL-set
    十分钟看懂图像语义分割技术
    命令行执行python模块时提示ImportError: No module named xxx
    python json与字典对象互相转换
    C#中json字符串的序列化和反序列化
    Python当前线程休眠1秒钟
    python之bytes和string
    Win32 基本文件读写操作
    C# 字符串与字节数组相互转换
  • 原文地址:https://www.cnblogs.com/inta/p/13362513.html
Copyright © 2020-2023  润新知