小明C#之冒泡排序

冒泡排序(Bubble Sort):

冒泡排序算法的原理如下:

  1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。

  2. 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

  3. 针对所有的元素重复以上的步骤,除了最后一个。

  4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

以下是代码实现(升序):

using System;

namespace bubbleSort
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 23, 44, 66, 76, 98, 11, 3, 9, 7 };
            Console.WriteLine("Before Bubble Sort: ");
            foreach (var item in arr)
            {
                Console.WriteLine(item+" ");
            }
            Console.WriteLine();
            Console.WriteLine("After Bubble Sort: ");
            bubbleSort(arr); //Invoke Bubble Sort method
            foreach(var itemSort in arr)
            {
                Console.WriteLine(itemSort+" ");
            }
            Console.ReadLine();
        }
        static void bubbleSort(int[] arr)
        {
            int i, j, temp;
            for (i = 0; i < arr.Length - 1; i++)
            {
                for (j = 0; j < arr.Length - 1 - i; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }

        }
    }
}
 

冒泡排序的时间复杂度为:最好的时间复杂度为O(n), 即所有的元素已经是有序的; 最坏的时间复杂度为O(n2), 所以平度时间复杂度为O(n2), 因为相同元素的前后顺序没有改变(因为相同元素是不会交换位置的), 冒泡排序是一个稳定的排序算法。

猜你喜欢

转载自blog.csdn.net/u010081392/article/details/88786667
今日推荐