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

 


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.严格的冒泡排序需要是从下往上的邻位比较,这样一来变换的次数就比较少

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值