1 //二分法 2 //假设顶一个已经排好序的数组,用户输入一个数,找出这个数的位置,没有则返回空 3 int[] nums = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 4 int a = 0, b = nums.Length - 1, zj; 5 Console.WriteLine("请输入要查找的数:"); 6 int n = Convert.ToInt32(Console.ReadLine()); 7 while (b >= a) 8 { 9 zj = (a + b) / 2;//中间数的下标 10 if (nums[zj] == n) 11 { 12 Console.WriteLine("找到了,在第{0}个", zj + 1); 13 break; 14 } 15 if (nums[zj] > n) 16 { 17 b = zj - 1;//把后面的数去掉 18 } 19 if (nums[zj] < n) 20 { 21 a = zj + 1;//把前面的数去掉 22 } 23 }
1 //二维数组 2 int[,] score = new int[3, 5]; 3 for (int i = 0; i < 3; i++)//循环每一行 4 { 5 Console.WriteLine("请输入第{0}位同学的成绩:", i + 1); 6 score[i, 0] = i + 1;//学号 7 //每一列需要从用户输入读取 8 Console.Write("C#:"); 9 score[i, 1] = Convert.ToInt32(Console.ReadLine()); 10 Console.Write("网页:"); 11 score[i, 2] = Convert.ToInt32(Console.ReadLine()); 12 Console.Write("数据库:"); 13 score[i, 3] = Convert.ToInt32(Console.ReadLine()); 14 score[i, 4] = score[i, 1] + score[i, 2] + score[i, 3];//总分 15 } 16 //冒泡排序,以总分成绩排名,score[i,4] 17 for (int i = 1; i <= 2; i++) 18 { 19 for (int j = 1; j <= 3 - i; j++) 20 { 21 if (score[j - 1, 4] < score[j, 4]) 22 { 23 for (int k = 1; k <= 5; k++)//把每一行所有列里面的内容交换 24 { 25 int s = score[j - 1, k - 1]; 26 score[j - 1, k - 1] = score[j, k - 1]; 27 score[j, k - 1] = s; 28 } 29 } 30 } 31 } 32 //打印这个二维数组 33 Console.WriteLine("学号\tC#\t网页\t数据库\t总分"); 34 for (int i = 0; i < 3; i++) 35 { 36 Console.Write(score[i, 0] + "\t"); 37 for (int j = 1; j < 4; j++) 38 { 39 Console.Write(score[i, j] + "\t"); 40 } 41 42 Console.Write(score[i, 4]); 43 Console.Write("\n"); 44 }
输出结果为:
时间: 2024-10-08 07:02:27