Bubble Sort (排序详解 之 冒泡排序)

Bubble Sort

This article,we will go through one easier sort algorithm --bubble sort .

Let's Startwith :

5 , 1, 9 ,3, 7 , 4 , 8 ,6 , 2

point :

1.from 1-n ,each time take 2 numbers ,number[k] and number[k+1]

2.comparethem ,if number[k] <(or > , depends on ascendingor descending) number[k+1] then swap them

now thissample is descending sort one array usingbubble sort .

Step 1,takefirst 2 numbers :


Step 2: Take1,9


Step 3: Take1,3


Repeat doingthe same thing ......

At last ,1 willbe the smallest one in thelast position .


so ,now gotit ? if we doing the same steps for 2nd round, we will get:


It is ,2 will be the 2nd one from the end just before 1.

so keep dong,next is 3:

Next is 4:


…… doing the same thing for n times .

finally , wewill get :

Hope now you are quite clear with bubble sort . :)



ReferenceCode :


public List<int> BubbleSort(List<int> arr)
        {
            var sortedArr = newList<int>();
            arr.ForEach(sortedArr.Add);
 
            if (arr.Count < 2) return arr;
 
            for (var i = sortedArr.Count; i> 0; i--)
            {
                for (var j = 1; j < i; j++)
                {
                    if (sortedArr[j - 1] >sortedArr[j])
                    {
                        int tmp = sortedArr[j -1];
                        sortedArr[j - 1] =sortedArr[j];
                        sortedArr[j] = tmp;
                    }
                }
            }
            return sortedArr;
        }
 

Finished .

Thanks forreading . :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值