冒泡排序

最近开始小小学习一些关于算法的东西。从最简单的开始。

简单的冒泡排序长这个样子

 public static void BubbleSortNormal(int[] temp)
        {
            for (int i = 0; i < temp.Length; i++)
            {
                for (int j = temp.Length - 1; j > i; j--)
                {

                    if (temp[j] < temp[j - 1])
                    {
                        Swap(ref temp[j], ref temp[j - 1]);
                    }
                }
            }
        }
        private static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }

但是这个样子的冒泡算法在已经完全排好序的情况下还会继续做出判断,还有优化的余地:

        public static void BubbleSortExpert(int[] temp)
        {
            Boolean canContinue = true;
            for (int i = 0; i < temp.Length && canContinue; i++)
            {
                canContinue = false;
                for (int j = temp.Length - 1; j > i; j--)
                {

                    if (temp[j] < temp[j - 1])
                    {
                        Swap(ref temp[j], ref temp[j - 1]);
                        canContinue = true;
                    }
                }
            }
        }

这里加了一个开关变量,当某次一个交换也没有就可以跳出循环了(因为已经全部排好序了)。

最后说一句,冒泡算法随机处理数据的规模为1000时,平均小于1ms,规模为10000时在700-800ms之间。如果 要做1000以下规模的排序,就冒泡好了~

你可能感兴趣的:(冒泡排序)