冒泡排序法是所有排序算法中最简单最基本的一种。冒泡排序法的思路的就是交换排序,通过相邻数据
的比较交换来达到排序的目的。
1.对数组中的各数据,依次比较相邻的两个元素的大小。
2.如果前面的数据大于后面的数据,就交换这个两个数据。
3.再用同样的方法把剩下的数据逐个进行比较,和交换。
#include <iostream>
using namespace std;
const int MaxNum = 10;
//len[] 为需要排序的数组,num为数组大小
void BubbleSort(int len[], int num)
{
int temp = 0;
for (int i = 0; i < num - 1; i++)
{
for (int j = num - 1; j > i; j--)
{
if (len[j - 1] > len[j]) //比较数组中数据的大小,交换
{
temp = len[j-1];
len[j-1] = len[j];
len[j] = temp;
}
}
}
}
int main()
{
int len[MaxNum] = { 10,23,45,14,17,3,9,94,46,76 };
cout << "排序前: ";
for (int i = 0; i < MaxNum; i++)
{
cout << len[i]<<"\t";
}
cout << endl;
cout << "排序后: ";
BubbleSort(len, MaxNum);
for (int i = 0; i < MaxNum; i++)
{
cout << len[i]<<"\t";
}
system("pause");
return 0;
}