冒泡排序算法的优化
#define _CTR_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
//冒泡排序
/*
冒泡排序算法如下:(升序排列)
1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2.对每一个相邻的元素作同样的工作,从开始第一队到结尾的最后一对。
在这一点,最后的元素应该会是最大的数。
3.针对所有的元素重复以上的步骤,除了最后一个。
4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较
稳定性:冒泡排序是一种稳定的排序算法
*/
void BubbleSort1(int* array, int len)//O(n2)
{
int count1 = 0;
int count2 = 0;
int flag = 0;//flag=0:说明还没有排序好 flag=1:则说明排好了
for (int i = 0; i < len&&flag==0; i++)
{
flag = 1;//一进来就默认,排序拍好了
for (int j = 1; j < len - i; j++)
{
count1++;
if (array[j] < array[j - 1])
{
int tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
flag = 0;
count2++;
}
}
}
cout << "比较的次数:" << count1 << endl;
cout << "交换的次数:" << count2 << endl;
}
#if 0
int main()
{
int array[] = { 1,5,7,9,8,4,3,5,12,10,9};
int len = sizeof(array) / sizeof(array[0]);
cout << "排序前:";
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
BubbleSort1(array, len);
cout << "排序后:";
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
#endif