冒泡排序
来源:互联网 发布:校园网络逻辑拓扑图 编辑:程序博客网 时间:2024/05/16 02:47
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); int[] array = { 42, 20, 17, 13, 28, 14, 23, 15 }; #region 冒泡排序 BubbleSort(array); #endregion sw.Stop(); Console.WriteLine("总运行时间:" + sw.Elapsed); Console.ReadLine(); } private static void PrintSortedResult(int[] inputArray, int num) { //打印操作结果 StringBuilder sb = new StringBuilder(); for (int i = 0; i < inputArray.Length; i++) { if (i == 0) { sb.Append(inputArray[i].ToString()); } else { sb.Append("," + inputArray[i].ToString()); } } Console.WriteLine("第" + num + "次排序的结果: " + sb.ToString() + "\r\n"); } private static void BubbleSort(int[] array) { for (int i = 0; i <= array.Length - 2;i++ ) { //i用来控制循环趟数 for (int j = array.Length - 1; j >= 1; j--) { if (array[j] < array[j - 1]) { int tmp = array[j]; array[j] = array[j - 1]; array[j - 1] = tmp; } } PrintSortedResult(array, i); } }