無論使用何種語言,在學習數組的時候我們接觸的第一個算法都會是這個排序算法。它有個好聽的名字冒泡排序。
冒牌排序(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 << " ";
}