排序算法系列之冒泡排序 (3)

一、冒泡排序

  1. 把长度为 l 的数组树立起来,从最底部n = l –1 开始,依次向上两两交换数据,每轮把最小的数据冒泡到顶部,使得顶部datas[o] – datas[i]为有序数组,底部datas[i] – datas[n] 为无序数组;
  2. 结束条件:排序好的数据长度为n-1,即(l-2)的时候,排序结束;
  3. 缺点:数据需要两两交换冒泡到顶部,中途哪怕遇到已经是适合位置的数据也需要被交换,而不能像选择排序一样跳过已经在合适位置的数据;
  4. 最坏情况:最大数据在最顶部,则会导致(n-1) !阶乘移动次数
  5. 代码如下:
    /// <summary>
        /// 冒泡排序,永远从底部开始,把相邻元素比较,交换,每轮把最小的依次浮到顶部
        /// </summary>
        public void BubbleSort<T>(T[] datas) where T : IComparable<T>
        {
            if (datas == null) return;
    
            for (int i = 0; i < datas.Length -1; i++)
            {
                for (int j = datas.Length -1; j > i; j--)
                {
                    if (datas[j].CompareTo(datas[j-1]) <0)
                    {
                        Swap(ref datas[j],ref datas[j -1]);
                    }
                }
            }
        }
  6. 测试数据:
    int[] BubbleDatas = { 5, 7, 3, 5, 2, 11, 90, 4, 2, 1, 3 };
    
            program.BubbleSort(BubbleDatas);
            DebugExtension.DebugArray(BubbleDatas);
  7. 测试结果:

               image

原文地址:https://www.cnblogs.com/liaoguipeng/p/5279200.html