c#算法(1)—冒泡排序

15 篇文章 7 订阅 ¥99.90 ¥299.90

前言:
冒泡排序的原理是(以升序为例)):
第一步、假如一共有N个数,从左边第一个数开始,从左到右把相邻的两个元素进行比较,如果右边的比左边的小,则调换两个元素位置,倒数第二个和倒数第一个元素比较完以后,最大的数此时已经在最右边了;
第二步、由于最右边的数已经是最大值了,所以再从左边第一个数开始和右边的数比较,一直比较到倒数第三个数和倒数第二个数;
第三步、以此类推,一直比较到第一个数和第二个数,比较的次数是N-1次。
1、升序

public List<int> BubbleSort_Ascend(List<int> list)
        {
            List<int> newList = new List<int>();
            newList = list.Select(item => item).ToList();
            int count = newList.Count;
            for (int i = 0; i < count-1; i++)
            {
                for (int j = 0; j < count - i - 1; j++)
                {
                    int first = newList[j];
                    int second = newList[j + 1];
                    if (second < first)
                    {
                        newList[j + 1] = first;
                        newList[j] = second;
                    }
                }
            }
            return newList;
        }

2、降序

public List<int> BubbleSort_Descend(List<int> list)
    {
        List<int> newList = new List<int>();
        newList = list.Select(item => item).ToList();
        int count = newList.Count;
        for (int i = 0; i < count-1; i++)
        {
            for (int j = 0; j < count - i - 1; j++)
            {
                int first = newList[j];
                int second = newList[j + 1];
                if (second > first)
                {
                    newList[j + 1] = first;
                    newList[j] = second;
                }
            }
        }
        return newList;
    }

调用:

 List<int> list = new List<int>() { 13, 1, 20, 15, 10, 23 };
            List<int> ascendList = BubbleSort_Ascend(list);
            ascendList.ForEach(item=>Console .WriteLine (item));
            List<int> descendList = BubbleSort_Descend(list);
            descendList.ForEach(item => Console.WriteLine(item));

输出

1
10
13
15
20
23

23
20
15
13
10
1
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

c#上位机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值