摘要
这篇文章将会讲解如何用C++实现冒泡排序算法。尽管STL库中已提供了排序函数,但是理解如何通过简单的循环实现冒泡排序算法还是有必要的。
原理
对于冒泡排序算法更简洁的理解,可访问网站https://visualgo.net/。
C++代码
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
int temp = 0;
vector<int> serial;
//Hint sentence to ask user input numbers.
cout << "Please input numbers with space to seperate and finished with any non-number character:" << endl;
//Use a vector as dynamic array to store numbers.
while(cin >> temp) serial.push_back(temp);
//To sort n numbers, there are n-1 number required to be swap.
for(int i = 0; i < serial.size()-1; i++)
{
//In the swap of each number, it requred to swap n-i times.
for(int j = 0; j < serial.size()-1-i; j++)
{
//If current number is larger than next number, swap them.
if(serial[j] > serial[j+1])
{
temp = serial[j];
serial[j] = serial[j+1];
serial[j+1] = temp;
}
}
}
//Print the result.
cout << endl << "From min to max:" << endl;
for(int i = 0; i < serial.size(); i++)
cout << serial[i] << " ";
cout << endl;
return 0;
}