冒泡法排序是一种比较简单的排序算法,算法复杂度为o(n2)(PS:最好最坏的情况下都是这样)
具体实现步骤为:
1、指定最末元素为初始比较值,与向上相邻的元素比较大小;
2、如果小于相邻元素,则交换顺序,相反,顺序不变;
3、以步骤2中向上相邻元素在与相邻元素对比,然后重复步骤2;
4、重复步骤2、3,直到最顶端位置,如下图所示:
5、重复n-1次结束
冒泡排序实现:
#include <iostream>
using namespace std;
template <class T> //获取数组长度模板函数
int getArrayLen(T& array)
{
return (sizeof(array) / sizeof(array[0]));
}
int main()
{
int data[15] = {1, 3, 6, 15, 2, 9, 10, 11, 7, 13, 8, 4, 12, 5, 14};
int data_size = getArrayLen(data); //数组长度
for (int i=1; i < data_size; i++) //循环次数
{
for(int j = data_size-1; j>0; j--) //数组元素排序
{
if(data[j]<data[j-1])
{
int temp = data[j];
data[j] = data[j-1];
data[j-1] = temp;
}
}
}
for(int k = 0; k < data_size; k++)
{
cout << data[k] << endl;
}
return 0;
}
其中,模板getArrayLen为读取整型数组的长度(C++中有直接读取字符数组长度的函数,不需要这个函数)