冒泡排序的优化及时间复杂度分析
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
void BubbleSort1(vector<int> a)
{
for (int i = 0; i < a.size() - 1; i++)
{
for (int j = a.size() - 1; j > 0; j--) //从后往前遍历
{
if (a[j] < a[j - 1])
{
a[j] = a[j] ^ a[j - 1];
a[j - 1] = a[j] ^ a[j - 1];
a[j] = a[j] ^ a[j - 1];
}
}
}
for (auto c : a)
{
cout << c << endl;
}
}
#if 0
冒泡排序属于交换排序类
改进后,遍历第n遍时如果数据没发生改变,则直接省略之后
多余的比较过程
时间复杂度分析:
最好情况:也就是排列前,表本身就是顺序的,则根据改进后
的方法需要进行n-1次比较,没有数据交换,时
间复杂度为O[n](注意是改进后的方法!!!)
最坏情况:也就是排列前,表是逆序的,则需要1+2+3+...+n-1
次,也就是n(n-1)/2次 时间复杂度为O[n^2]
#endif
void BubbleSort2(vector<int> a)
{
bool flag = true; //通过设置标记来改进算法
for (int i = 0; i < a.size() - 1 && flag; i++)
{
flag = false; //初始为false
for (int j = a.size() - 1; j > 0; j--) //从后往前遍历
{
if (a[j] < a[j - 1])
{
a[j] = a[j] ^ a[j - 1];
a[j - 1] = a[j] ^ a[j - 1];
a[j] = a[j] ^ a[j - 1];
flag = true; //发生数据交换则变为true
}
}
}
for (auto c : a)
{
cout << c << endl;
}
}
int main(int argc,char *argv[])
{
vector<int> a = { 5, 8, 2, 1, 9, 56, 33, 98, 123, 66 };
vector<int> b = { 1, 2, 3, 4, 5, 6, 7, 8 };
BubbleSort2(a);
BubbleSort2(b);
return 0;
}