您的位置:首页 > 编程语言 > C语言/C++

鸡尾酒排序(类似冒泡排序)

2014-04-14 02:25 357 查看
鸡尾酒排序,实际上是从左右两端交替使用冒泡排序;
例:5  18  9  17 53 23 78
先从最右边开始,比较 23  78-->23  78               5  18  9  17  53  23  78
53  23-->23  53               5  18  9  17  23  53  78
17  23-->17  23               5  18  9  17  23  53  78
9   17-->9   17               5  18  9  17  23  53  78
18  9 -->9   18               5  9  18  17  23  53  78
5   9 -->5   9                5  9  18  17  23  53  78
再从左边开始,第一趟已经将最小数排到下标为0处,所以这次排序下标从1开始:
9  18-->9  18                 5  9  18  17  23  53  78
18  17-->17  18               5  9  17  18  23  53  78
18  23-->18  23               5  9  17  18  23  53  78
23  53-->23  53               5  9  17  18  23  53  78
53  78-->53  78               5  9  17  18  23  53  78
再从右边开始,下标从5开始,如此左右交替,

C++ 实现代码:
#include<iostream>
using namespace std;
void CocktailSort(int *a,int m){
   int n=m-1; //注意此处
for(int i=0;i<n;)
{
       for(int j=n;j>i;--j) //从后往前遍历一次,求出最小值;循环执行一次后,注意下标变化;
 {   int temp;
if(a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
  ++i;
for(int j=i;j<n;++j)//从前往后遍历一次,求出最大值;注意开始位置下标改变;
 {   int temp;
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
 }
  --n;
}

}

int main()
{
int a[]={53,78,90,21,51,789,852,567,765,8908,253212,32,908};//随机定义的数组
int m=sizeof(a)/sizeof(*a);
CocktailSort(a,m);
int count=0;
for(int index=0;index<m;++index)
{   cout<<a[index]<<"\t";
count++;
if(count%8==0)
cout<<endl;
}
if(m%8!=0)
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  鸡尾酒排序 C++ 排序