namespace SortArithmetic { public class MyClass { public static void Main() { int[] Nums = RandomNums(3, 27); ShowNums("原数组是: ", Nums); //ShowNums("排序后是:", BubbleSort(Nums)); ShowNums("排序后是:", SelectSort(Nums)); Console.ReadLine(); }
#region 生成随机int数组 private static int[] RandomNums(int Length, int Count) { Random Rand = new Random(7); int[] Nums = new int[Count]; for (int c = 0; c < Count; c++) { string Result = string.Empty; for (int i = 0; i < Length; i++) { Result += Rand.Next(10).ToString(); } Nums[c] = Convert.ToInt32(Result); } return Nums; } #endregion
#region 排序算法:冒泡排序(升序) 排序次数可计算:int[n],n为5那么 6*(6-1)/2 private static int[] BubbleSort(int[] Nums) { for (int c = 0; c < Nums.Length-1; c++) { for (int i = 0; i < Nums.Length - c - 1; i++) { int Temp = Nums[i + 1]; if (Nums[i] > Nums[i + 1]) { Nums[i + 1] = Nums[i]; Nums[i] = Temp; } } } return Nums; } #endregion
#region 排序算法:选择排序(升序) private static int[] SelectSort(int[] Nums) { for (int c = 0; c < Nums.Length-1; c++) { for (int i = c; i < Nums.Length - 1; i++) { int Temp = Nums[i+1]; if (Nums[c] > Nums[i + 1]) { Nums[i + 1] = Nums[c]; Nums[c] = Temp; } } } return Nums; } #endregion