C# 冒泡算法

C# 冒泡算法,改良的冒泡算法,可以提高效率,注意:第一次假如就是顺序的话,就直接退出循环。

static void Main(string[] args)
        {
            int[] arrs = {20,21,24,24,56,78,90,20,78,98};
            //数组的定义3种:
            int[] arrs1 = { 1,2,4};
            int[] arrs2=new int[3];
            int[] arrs3 = new int[] {1,3,3,3,3,3,3,4 };
           
            //进行冒泡排序
            //外层循环将最大值放最后
            for (int i = 0; i <arrs.Length-1; i++)
            {
                bool flag=true;  //冒泡排序优化说明:当发现前面已经不在交换,证明已经是有序队列,故结束整个循环的排序
                //看第一次排序是否已经是有序队列
                //内层循环将两两交换
                for (int j = 0; j< arrs.Length-1-i; j++)
                {
                    flag = true;
                    int temp=0;
                    if ( Convert.ToInt32(arrs[j])> Convert.ToInt32(arrs[j+1]))
                    {
                        temp = arrs[j + 1];
                        arrs[j+1]=arrs[j];
                        arrs[j] = temp;
                        flag = false;
                    }
                }
                if (flag == false)
                {
                    break;
                }
            }
            foreach (var item in arrs)
            {
                Console.Write("{0} ",item);
            }
            Console.ReadKey();
        }

相关推荐