算法1:BubbleSort
2010-05-02 16:35 Li Qian 阅读(301) 评论(1) 收藏 举报
代码
#include <iostream>
using namespace std;
#define LEN 6
void MyPrint(int *n,int count);
void main()
{
int array[LEN]={4,5,7,1,2,3};
cout<<"Original Array:"<<endl;
MyPrint(array, LEN);
//add a flag which type is bool
//bool flag=true;
int loopCount=0;
int exchangeCount=0;
int temp=0;
for(int i=LEN-1;i>0;i--)
{
// if(true == flag)
// {
for(int j=0;j<i;j++)
{
if (array[j]<array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
exchangeCount++;
// flag=true;
}
// else
// flag=false;
//
}
loopCount++;
// }
// else
// break;
}
cout<<"New Array:"<<endl;
MyPrint(array, LEN);
cout<<"The number of exchange:"<<exchangeCount<<endl;
cout<<"The number of out Loop:"<<loopCount<<endl;
}
void MyPrint(int *n, int count)
{
for(int i=0;i<count;i++)
cout<<n[i]<<" ";
cout<<endl;
}

去掉注释优化后的结果

若记录为"正序",只需一趟排序,进行n-1次比较,不移动记录;
若为"逆序",需要n*(n-1)/2比较和移动.
时间复杂度O(n*n).
比较移动次数
如 1 2 3 4
2 3 4 1 3
3 4 2 1 2
4 3 2 1 1

浙公网安备 33010602011771号