#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
#define random(x,y) (rand()%(y-x)+x)
#define length(a) (sizeof(a)/sizeof(a[0]))
int main(){
srand((int)time(0));
int count=0;
int s = 10;
int array[s];
int array1[s];
int array2[s];
memset(array,0,sizeof(array));
memset(array1,0,sizeof(array1));
memset(array2,0,sizeof(array2));
cout<<"排序前:";
for(int i = 0;i<length(array);i++){
array[i] = random(1,100);
cout<<setw(4)<<array[i];
}
memcpy(array1, array,sizeof(array));
memcpy(array2, array,sizeof(array));
//冒泡排序
for(int i = 0;i<length(array)-1;i++){
for(int j = 0;j<(length(array)-1)-i;j++){
if(array[j]>array[j+1]){//按从小到大排列
swap(array[j],array[j+1]);
}
count++;
}
}
cout<<endl<<"排序后:";
for(int i = 0;i<length(array);i++){
cout<<setw(4)<<array[i];
}
cout<<endl<<"循环次数:"<<count<<endl;
//优化-1
count = 0;
cout<<"排序前:";
for(int i = 0;i<length(array1);i++){
cout<<setw(4)<<array1[i];
}
//冒泡排序
for(int i = 0;i<length(array1)-1;i++){
int flag = 0; //设置一个标志位
for(int j = 0;j<(length(array1)-1)-i;j++){
if(array1[j]>array1[j+1]){//按从小到大排列
swap(array1[j],array1[j+1]);
flag = 1;
}
count++;
}
if(flag==0) break;//内层循环没有改变标志位则表示数组已 排序完成,提前跳出循环
}
cout<<endl<<"排序后:";
for(int i = 0;i<length(array1);i++){
cout<<setw(4)<<array1[i];
}
cout<<endl<<"循环次数:"<<count<<endl;
//优化-2
count = 0;
cout<<"排序前:";
for(int i = 0;i<length(array2);i++){
cout<<setw(4)<<array2[i];
}
//冒泡排序
int flag;
int pos;
int posflag = length(array2)-1;
for(int i = 0;i<length(array2)-1;i++){
flag = 0; //设置一个标志位
pos=0;
for(int j = 0;j<posflag;j++){
if(array2[j]>array2[j+1]){//按从小到大排列
swap(array2[j],array2[j+1]);
flag = 1;
pos = j;//记录每次大循环置换的最后一个数组的的下标
}
count++;
}
if(flag==0)break;//内层循环没有改变标志位则表示数组已排序完成,提前跳出循环
posflag = pos;
}
cout<<endl<<"排序后:";
for(int i = 0;i<length(array2);i++){
cout<<setw(4)<<array2[i];
}
cout<<endl<<"循环次数:"<<count<<endl;
return 0;
}