您的位置:首页 > 其它

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

2013-08-12 18:36 337 查看

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 . :)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  排序 冒泡排序 算法
相关文章推荐