算法 - 冒泡排序(C#)
分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
// --------------------------------------------------------------------------------------------------------------------// <copyright file="Program.cs" company="Chimomo's Company">//// Respect the work.//// </copyright>// <summary>//// The bubble sort.//// 冒泡排序(Bubble Sort),是一种计算机科学领域较简单的排序算法。它重复地走访要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来,直到没有元素再需要交换为止。这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。//// 冒泡排序的算法如下:// 1、对无序区的每一对相邻元素作比较,从开始第一对到最后一对,如果相邻元素对中的第一个比第二个大,就交换他们两个。从而,最后一个元素必定是最大元素,把该最大元素移出无序区。// 2、持续对越来越少的无序区元素重复上面的步骤,直到没有任何一对元素需要比较为止。//// 时间复杂度:// 冒泡排序的平均时间复杂度为O(n^2)。//// 算法稳定性:// 冒泡排序就是把大的元素往后调。比较是相邻的两个元素作比较,交换也发生在这两个元素之间。所以,如果两个元素相等,我想你是不会再无聊地把他们俩交换一下的;如果两个相等的元素没有相邻,那么即使通过前面的元素交换把这两个相等相邻起来,这时候也不会交换。所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定的排序算法。//// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{ using System; /// <summary> /// The program. /// </summary> public static class Program { /// <summary> /// 冒泡排序算法。 /// </summary> /// <param name="a"> /// 待排序数组。 /// </param> private static void BubbleSort(int[] a) { Console.WriteLine("In Bubble Sort:"); // 外循环是限制一次冒泡排序比较的元素个数。 for (int i = a.Length - 1; i >= 1; i--) { // 内循环比较0到i-1个元素的大小。 for (int j = 0; j <= i - 1; j++) { // 排序过程。 if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; } } Console.Write("Round {0}: ", a.Length - i); foreach (int k in a) { Console.Write(k + " "); } Console.WriteLine(); } } /// <summary> /// The main. /// </summary> public static void Main() { int[] a = { 1, 6, 4, 2, 8, 7, 9, 3, 10, 5 }; Console.WriteLine("Before Bubble Sort:"); foreach (int i in a) { Console.Write(i + " "); } Console.WriteLine("\r\n"); BubbleSort(a); Console.WriteLine("\r\nAfter Bubble Sort:"); foreach (int i in a) { Console.Write(i + " "); } Console.WriteLine(string.Empty); } }}// Output:/*Before Bubble Sort:1 6 4 2 8 7 9 3 10 5In Bubble Sort:Round 1: 1 4 2 6 7 8 3 9 5 10Round 2: 1 2 4 6 7 3 8 5 9 10Round 3: 1 2 4 6 3 7 5 8 9 10Round 4: 1 2 4 3 6 5 7 8 9 10Round 5: 1 2 3 4 5 6 7 8 9 10Round 6: 1 2 3 4 5 6 7 8 9 10Round 7: 1 2 3 4 5 6 7 8 9 10Round 8: 1 2 3 4 5 6 7 8 9 10Round 9: 1 2 3 4 5 6 7 8 9 10After Bubble Sort:1 2 3 4 5 6 7 8 9 10*/
还没有评论,来说两句吧...