冒泡排序的思想是:从头访问待排序的数列,每次比较相邻的两个元素,将他们的顺序按照从大到小或者从小到大调整过来,直到完成整个数列所有元素的顺序调整。
动态效果示意图如下:
C++代码
#include <iostream>
using namespace std;
#include <vector>
vector<int>BubbleSort(vector<int> list)
{
vector<int>result = list;
if (result.empty())
{
return result;
}
for (int i = 0; i < result.size() - 1; i++)
{
int temp; //临时存储交换值的变量
cout << "第" << i + 1 << "次排序的排序结果" << endl;
for (int j = 0; j < result.size() - 1; j++)
{
if (result[j + 1] < result[j])
{
temp = result[j + 1];
result[j + 1] = result[j];
result[j] = temp;
}
}
for (int k = 0; k < result.size(); k++)
{
cout << result[k] << " ";
}
cout << endl;
}
return result;
}
int main()
{
int arr[] = { 6, 4, 8, 1, 2, 3, 9 };
vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0]));
cout << "排序前" << endl;
for (int i = 0; i < test.size(); i++) {
cout << test[i] << " ";
}
cout << endl;
vector<int> result;
result = BubbleSort(test);
cout << "排序后" << endl;
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
system("pause");
}
运行结果如下:
冒泡排序最好的时间复杂度为:O(n);
最坏的时间复杂度为:O(n^2);
平均时间复杂度为:O(N^2);
冒泡排序算法需要一个临时辅助空间temp,故辅助空间为O(1);
冒泡排序是稳定的排序方法
对冒泡排序进行优化:
有时会有这样的情况:
当一组数字,部分有序时,比如{49, 38, 65, 97, 76, 13, 27, 30},我们不必每次都从头到尾的去访问,两两交换位置,只需进行四次排序就可以完成从小到大的排序结果,那么我们可以在代码中增加一个标志位,当开始这次的访问时,根据标志位的符号,决定是否进行访问遍历。
代码如下:
#include <iostream>
using namespace std;
#include <vector>
vector<int>BubbleSort(vector<int> list)
{
vector<int>result = list;
if (result.empty())
{
return result;
}
bool flag = true; //增加标志位作为是否向下执行的标志
for (int i = 0; i < result.size() - 1 && flag == true; i++)
{
flag = false;
int temp; //临时存储交换值的变量
cout << "第" << i + 1 << "次排序的排序结果" << endl;
for (int j = 0; j < result.size() - 1; j++)
{
if (result[j + 1] < result[j])
{
flag = true;
temp = result[j + 1];
result[j + 1] = result[j];
result[j] = temp;
}
}
for (int k = 0; k < result.size(); k++)
{
cout << result[k] << " ";
}
cout << endl;
}
return result;
}
int main()
{
int arr[] = { 6, 4, 8, 1, 2, 3, 9 };
vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0]));
cout << "排序前" << endl;
for (int i = 0; i < test.size(); i++) {
cout << test[i] << " ";
}
cout << endl;
vector<int> result;
result = BubbleSort(test);
cout << "排序后" << endl;
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
system("pause");
}
排序结果如下:
此时便可以在一定程度上提高冒泡排序的效率
参考:
https://www.bilibili.com/video/av38482485
https://cuijiahua.com/blog/2017/12/algorithm_1.html