您的位置:首页 > 其它

排序算法之——冒泡排序

2015-09-10 15:16 337 查看
排序算法中冒泡应该算是比较简单的,但是效率比较低,不适合大规模的数据排序。

先上代码:

void prinary(int *a,int n);
inline unsigned __int64 GetCycleCount();
void Bubble1(int *a,int n);
void Bubble2(int *a,int n);

int counts=0;
int _tmain(int argc, _TCHAR* argv[])
{
counts = 0;
int ary1[10] = {5,7,6,3,2,8,9,4,1,0};
unsigned __int64 time = GetCycleCount();
Bubble1(ary1,10);
prinary(ary1,10);
cout<<"maopao1 time = "<<GetCycleCount()-time<<"and call ="<<counts<<endl;

counts = 0;
int ary2[10] = {5,7,6,3,2,8,9,4,1,0};
time = GetCycleCount();
Bubble2(ary2,10);
prinary(ary2,10);
cout<<"maopao2 time = "<<GetCycleCount()-time<<"and call ="<<counts<<endl;

return 0;
}
void swap(int &a,int &b)
{
int c;
c = a;
a = b;
b = c;
}
void prinary(int *a,int n)
{
for(int i = 0; i<n; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
//得到cpu时钟时间
inline unsigned __int64 GetCycleCount()
{
__asm _emit 0x0F
__asm _emit 0x31
}
//冒泡1,升序
void Bubble1(int *a,int n)
{
for(int i = 0; i<n-1; i++)
{
for(int j = 0; j<n-1; j++)
{
counts++;
if( a[j]>a[j+1] )
{
swap(a[j],a[j+1]);
}
}
}
}
//冒泡2,升序
void Bubble2(int *a,int n)
{
int j;
for(int i = 1; i<n; i++)
{
j = i;
while(1)
{
counts++;
if(j>n || j<0)
{
break;
}
if(a[j] < a[j-1])
{
swap(a[j],a[j-1]);
j--;
}
else
{
break;
}
}
}
}


我写了两个冒泡算法,一个是基于“重泡泡”往下沉,另一种是基于“轻泡泡”往上飘,其实我个人觉得第二种更贴合这个算法的名字,毕竟泡泡都是想要往上挤的。

现在看看输出:

0 1 2 3 4 5 6 7 8 9

maopao1 time = 4993972and call =81

0 1 2 3 4 5 6 7 8 9

maopao2 time = 1615260and call =39

从输出可以看出两个函数都完成了数组的排序,但是却有很大的区别:

从时间上和循环次数上看,第二种算法明显优于第一种,因为第一种算法没有任何跳出的语句,也就是说数组的大小决定了它循环的次数。而第二种是有“判断”的循环,如果没有必要再循环下去那么就跳出。

但是也不能说第二种就比第一种好,第一种一次循环就一个swap,而第二种一次循环有三个判断和一个swap,所以说算法没有最好的,只有最合适的~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: