您的位置:首页 > 其它

复习一下冒泡排序和其改进

2017-07-21 16:26 274 查看


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace text

{

    //=============冒泡

    class MyClass

    {

        public void bubble(int[] a)

        {

            bool flag = true;

            for (int i = 0; i < a.Length && flag; i++)

            {

                flag = false;

                for (int j = a.Length - 1; j > i; j--)

                    if (a[j] < a[j - 1])

                    {

                        int temp = a[j];

                        a[j] = a[j - 1];

                        a[j - 1] = temp;

                        flag = true;

                    }

            }

        }

    }

    class Program

    {

        //============洗牌

        static void shuffle(int[] x)

        {

            Random random = new Random();

            for (int i = 0; i < x.Length - 2; i++)

            {

                int tempIndex = random.Next(i + 1, x.Length - 1);

                int k = x[i];

                x[i] = x[tempIndex];

                x[tempIndex] = k;

            }

            foreach (int item in x)

            {

                Console.Write(item + ",");

            }

            Console.Write("\n");

        }

        static void Main(string[] args)

        {

            int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            shuffle(a);

            MyClass myClass = new MyClass();

            myClass.bubble(a);

            Console.WriteLine("冒泡:");

            foreach (int item in a)

            {

                Console.Write(item + ",");

            }

        }

    }

}

 

改进后添加哨兵,如果从下往上做判断而没有发生交换,那么后续判断就不需要进行了

ps.严格的冒泡排序需要是从下往上的邻位比较,这样一来变换的次数就比较少
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: