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

来源:互联网 发布:同步助手java 编辑:程序博客网 时间:2024/06/06 01:14

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 . :)