无论使用何种语言,在学习数组的时候我们接触的第一个算法都会是这个排序算法。它有个好听的名字冒泡排序。
冒牌排序(Bubble Sort) 一种交换排序,它的基本思想就是:两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void BubbleSort(vector<int> & s);
void Show(int x);
int main()
{
using namespace std;
vector<int> input = { 40, 8, 15, 18, 12 }; //待排序数据
BubbleSort(input);
for_each(input.begin(), input.end(), Show);
cin.get();
return 0;
}
void BubbleSort(vector<int> & s)
{
for (int i = 0; i < s.size()-1; i++) //第i趟排序
{
for (int j = 0; j < s.size()-i-1; j++)
{
if (s[j]>s[j + 1]) //反序则交换
{
int temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
}
void Show(int x)
{
cout << x << " ";
}