C#M面试题之——冒泡排序

    xiaoxiao2021-12-14  17

    1 //定义数组 2 static int[] nums = new int[] { 100, 99, 45, 56, 67, 78, 98, 8, 7, 65, 55, 43, 32, 23, 35, 36, 38, 37, 120, 150, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 30, 32, 31, 29, 28, 26, 27, 25, 22, 24 }; 3 static void Main(string[] args) 4 { 5 Console.WriteLine("冒泡排序之传统方法"); 6 BubblingOne(); 7 Console.ReadKey(); 8 } 9 /// <summary> 10 /// 冒泡排序,传统数据交换实现 11 /// </summary> 12 static void BubblingOne() 13 { 14 //定义一个需要排序的数组 15 16 //定义一个临时变量用于数据交换 17 int temp; //临时变量,保存最大值 18 int i, j; //循环变量 19 for (i = 0; i < nums.Length - 1; i++) 20 { 21 for (j = 0; j < nums.Length - 1 - i; j++) 22 { 23 if (nums[j] < nums[j + 1]) 24 { 25 temp = nums[j]; 26 nums[j] = nums[j + 1]; 27 nums[j + 1] = temp; 28 } 29 } 30 } 31 foreach (int c in nums) //用foreach输出排序后的数组元素 32 { 33 Console.Write(c + "\t"); 34 } 35 } 请注意我们实现了泛型接口IEnumerable<T> IEnumerable<T> 是一个接口,通过该接口,可以使用 foreach 语句来枚举泛型集合类。 泛型集合类支持 IEnumerable<T>,就像非泛型集合类(如ArrayList)支持 IEnumerable。 运行结果和第一种方法一致. 你可能已经发现了,代码简洁了许多,有原来的8行缩短为一行,这不正是我们的追求吗?尤其是在面试的时候是否为你节约了大量的时间? 那是否还有其他的方式继续实现冒泡排序呢?答案是肯定的,记住我们是对数组中的数据进行操作,Linq有两个扩展方法OrderByDescending和OrderBy用于对数据排序,请参见:对数据进行排序 1 /// <summary> 2 /// linq 冒泡排序算法 3 /// </summary> 4 static void BubblingTwo() 5 { 6 IEnumerable<int> num = from a in nums orderby a descending select a; 7 foreach (int item in num) 8 { 9 Console.Write(item + "\t"); 10 } 11 } 这只是个人比较常用的两种,相信肯定还有很多简便的方法,希望能与各位大牛多多学习!!!
    转载请注明原文地址: https://ju.6miu.com/read-969151.html

    最新回复(0)