#include <iostream>
#include <vector>
using namespace std;
//相邻元素进行比较 每一趟都有最大元素排好
template<typename Comp>
void BubbleSort1(vector<Comp> &a) //经典冒泡排序 O(N^2)
{
int i = 0;
int j = 0;
for(i = 0; i < a.size(); i++)
{
for (int j = 1; j < a.size()-i; j++)
{
if (a[j-1] > a[j])
{
Comp tmp = a[j-1];
a[j-1] = a[j];
a[j] = tmp;
}
}
}
}
template<typename Comp>
void BubbleSort2(vector<Comp> &a) //优化冒泡排序
{
int i = 0;
int j = 0;
int flag = 1; //如果序列有序置0 无序置1
for(i = 0; i < a.size() && flag; i++) //如果序列有序 则不需要再排序
{
flag = 0;
for (int j = 1; j < a.size()-i; j++)
{
if (a[j-1] > a[j]) //如果前置元素比后置元素大 则交换位置
{
flag = 1;
Comp tmp = a[j-1];
a[j-1] = a[j];
a[j] = tmp;
}
}
}
}
void main()
{
vector<int> a;
a.push_back(8);
a.push_back(3);
a.push_back(6);
a.push_back(1);
cout << "排序前:";
for(int i = 0; i < a.size(); i ++)
cout << a[i] << " ";
cout << endl;
BubbleSort1(a);
cout << "排序后:";
for(int i = 0; i < a.size(); i ++)
cout << a[i] << " ";
cout << endl;
system("pause");
}
01_冒泡排序
最新推荐文章于 2023-06-16 13:42:34 发布