前言:
冒泡排序的原理是(以升序为例)):
第一步、假如一共有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