本冒泡排序输出了每轮排序的过程,同时可以判断什么时候排序完成,并break退出总循环.
不判断排序是否完成,程序大部分情况下会继续执行,知道循环变量达到临界条件,然而会增加许多运算量、
判断排序是否完成的目的是减少 时间复杂度
(我觉得减少了。。。没做具体推算)
下篇博文给出不加判断排序是否完成的程序运行的结果
#include <iostream>
#define N 100
using namespace std;
int main()
{ int a[N] = {8,10,60,4,99,3,180,13,6,15,16,17};
int temp,num = 0;
int stop = 0,Stop = 0;
int solvetimes = 0,loop = 0;
cout<<"start solving"<<endl;
for(int k = 0;k<N;k++)
if(a[k]!=0)
num = k+1;
for(int i = 0;i<num;i++){
cout<<"第"<<i+1<<"轮排序"<<endl;
for( int j = 0;j<num-i-1;j++){
if( a[j]>a[j+1] ){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
for(int k = 0;k<num;k++)
cout<<a[k]<<" ";
cout<<endl;
solvetimes++; }
loop++; }
Stop = 0;
for(int l = 0;l<num;l++){
if( a[l]<=a[l+1] )
stop = 1;
else stop = 0;
Stop+=stop;
}
if(Stop == num - 1) //n个元素两两比较只需要 n-1 次
break; //cout<<Stop<<endl;
}
cout<<"\nsolving successful!\n"<<endl;
cout<<"对 " <<num<<" 个数进行排列"<<endl;
cout<<"共进行交换"<<solvetimes<<"次"<<endl;
cout<<"第二循环共执行"<<loop<<"次"<<endl; //含判断是否交换的for循环语句
cout<<"排序结果为:"<<endl;
int i = 0;
while(i<num){
cout<<a[i]<<" ";
i++;
}
return 0;
}
下面给出运行结果图