C++:冒泡排序
Posted davcloud
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++:冒泡排序相关的知识,希望对你有一定的参考价值。
声明:本文全部内容为原创内容,禁止在未经授权的情况下进行任何二次创作和修改,转载请注明出处。
摘要
这篇文章将会讲解如何用C++实现冒泡排序算法。尽管STL库中已提供了排序函数,但是理解如何通过简单的循环实现冒泡排序算法还是有必要的。
原理
对于冒泡排序算法更简洁的理解,可访问网站https://visualgo.net/。
C++代码
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;
}
--------------------------------------------
This part is for the least words requirement for a article. You can see this because the topic for this article is easy to describe but still need more words so that it can be published as an original article, don't care about this!
--------------------------------------------
个人博客主站(最新内容):https://blog.davcloud.top:1443
CSDN:不向光的红外线
知乎:不向光的红外线
以上是关于C++:冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章