C#冒泡排序和选择排序
using System; namespace ConsoleApp03 { /// <summary> /// C#冒泡排序和选择排序 /// LDH @ 2018-4-18 /// </summary> internal class Program { private static void Main() { Console.Title = "C#冒泡排序和选择排序"; PlaySort(); Console.ReadKey(); } /// <summary> /// 玩转排序 /// </summary> private static void PlaySort() { var array = new int[10]; var random = new Random(); for (var i = 0; i < array.Length; i++) { array[i] = random.Next(60, 100); } Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("未排序前的随机数组为:"); foreach (var t in array) { Console.ForegroundColor = ConsoleColor.White; Console.Write(t + "\t"); } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("选择排序(S),冒泡排序(B),退出程序(Q)"); while (true) { var input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("选择排序(S),冒泡排序(B),退出程序(Q)"); } else { input = input.ToUpper().Trim(); switch (input) { case "S": SelectSort(array); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("选择排序如下:"); OutputArray(array); Console.WriteLine(); break; case "B": BubbleSort(array); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("冒泡排序如下:"); OutputArray(array); Console.WriteLine(); break; case "Q": Console.WriteLine("回车退出程序!"); return; } } } } /// <summary> /// 输出数组元素 /// </summary> /// <param name="array">要输出元素的数组</param> private static void OutputArray(int[] array) { for (var i = 0; i < array.Length; i++) { Console.Write(array[i] + "\t"); } Console.WriteLine(); } /// <summary> /// 冒泡排序 /// </summary> /// <param name="array">要排序的数组</param> private static void BubbleSort(int[] array) { for (var i = 0; i < array.Length - 1; i++) { for (var j = 0; j < array.Length - 1 - i; j++) { if (array[j] > array[j + 1]) { var temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } } } /// <summary> /// 选择排序 /// </summary> /// <param name="array">要排序的数组</param> private static void SelectSort(int[] array) { for (var i = 0; i < array.Length; i++) { for (var j = i + 1; j < array.Length; j++) { if (array[i] > array[j]) { var temp = array[j]; array[j] = array[i]; array[i] = temp; } } } } } }
版权声明:本文为LifeDecidesHappiness原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。