排序-Bubble
2022-02-18 本文已影响0人
我阿郑

算法描述
- 比较相邻的元素。如果第一个比第二个大,就交换它们两个;
- 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数;
- 针对所有的元素重复以上的步骤,除了最后一个;
- 重复步骤1~3,直到排序完成。
具体代码实现
namespace BubbleSort
{
template <typename T>
// n是元素个数
void sort(T arr[], int length)
{
if (length < 0)
{
return;
}
// 外层for控制比较轮数,轮数从1到length-1
for (int i = 1; i < length - 1; i++)
{
// 内层for控制每一轮比较次数
// 比较次数 = length - 当前轮数i (轮数从1开始的)
for (int j = 0; j < length - i; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
}
}