标签:
1、写个函数完成:
1)输入10个职工的职工号和姓名;
2)按职工号由小到大顺序排序,姓名顺序也随之调整;
3)要求输入一个职工号,用折半查找法找出该职工的姓名,输入要查找的职工号,输出该职工的姓名。
主要代码:
static void Main(string[] args) { Program function = new Program(); function.workers(); Console.ReadLine(); } public void workers() { //输入职工号、职工姓名用二维数组装。 string[,] worker = new string[10, 2]; int[] num = new int[10];//记录职工号。 for (int i = 0; i < 10; i++) { Console.Write("请输入职工号:"); worker[i, 0] = Console.ReadLine(); Console.Write("请输入职工姓名:"); worker[i, 1] = Console.ReadLine(); num[i] = int.Parse(worker[i, 0]); } Console.WriteLine(); Console.WriteLine("排序前:"); Console.WriteLine("职工号\t姓名"); for (int i = 0; i < 10; i++) { for (int j = 0; j < 2; j++) Console.Write(worker[i, j] + "\t"); Console.WriteLine(); } Console.WriteLine(); //用哈希表装数组中职工号和职工姓名 Hashtable work = new Hashtable(); for (int i = 0; i < 10; i++) { work.Add(int.Parse(worker[i, 0]), worker[i, 1]); } //用ArrayList集合对哈希表键进行排序 ArrayList w = new ArrayList(work.Keys); w.Sort(); Console.WriteLine("排序后:"); Console.WriteLine("职工号\t姓名"); for (int i = 0; i < w.Count; i++) { Console.WriteLine("{0}\t{1}", w[i], work[w[i]].ToString()); } //用冒泡法对职工号数组进行排序 int t; for (int j = 0; j < 9; j++) { for (int i = 0; i < 9 - j; i++) { if (num[i] > num[i + 1]) { t = num[i]; num[i] = num[i + 1]; num[i + 1] = t; } } } Console.WriteLine(); //输入职工号输出职工姓名 while (true) { Console.Write("请输入职工号:"); int n = int.Parse(Console.ReadLine()); int min = 0, max = 10, mid; //折半查找法 while (min + 1 != max) { mid = (max + min) / 2; if (n > num[mid]) { min = mid; } else if (n < num[mid]) { max = mid; } else { Console.WriteLine("{0}号职工的姓名为{1}。", n, work[n].ToString()); break; } } if (n == num[max]) Console.WriteLine("{0}号职工的姓名为{1}。", n, work[n].ToString()); else if (n == num[min]) Console.WriteLine("{0}号职工的姓名为{1}。", n, work[n].ToString()); else if (n != num[0] && n != num[1] && n != num[2] && n != num[3] && n != num[4] && n != num[5] && n != num[6] && n != num[7] && n != num[8] && n != num[9]) Console.WriteLine("{0}号职工不存在。", n); } }
结果:
标签:
原文地址:http://www.cnblogs.com/bosamvs/p/5493392.html