经典排序算法-鸡尾酒排序CocktailSort
鸡尾酒排序(改进的冒泡排序),原理是对要排序的数组进行双向冒泡排序,双向冒泡排序又称为鸡尾酒排序。
其示例代码如下:
#include <IOSTREAM>
using namespace std;
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**/////////鸡尾酒排序/双向冒泡排序(改进的冒泡排序)
void CocktailSort(int *a,int nsize)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
int tail=nsize-1;
for (int i=0;i<tail;)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for (int j=tail;j>i;--j) //第一轮,先将最小的数据排到前面
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (a[j]<a[j-1])
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
++i; //原来i处数据已排好序,加1
![](/Images/OutliningIndicators/InBlock.gif)
for (j=i;j<tail;++j) //第二轮,将最大的数据排到后面
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (a[j]>a[j+1])
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
tail--; //原tail处数据也已排好序,将其减1
}
}
void OutPut(int *b,int nLength)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
for (int i=0;i<nLength;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
cout<<b[i]<<'\t';
}
cout<<endl;
}
int main()
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int nData[]=
{1,4,2,5,67,86,24,63,676,23,1,3,2,34};
![](/Images/OutliningIndicators/InBlock.gif)
CocktailSort(nData,sizeof(nData)/sizeof(nData[0]));
OutPut(nData,sizeof(nData)/sizeof(nData[0]));
return 1;
}
posted on 2012-05-28 19:58
代码之美 阅读(1962)
评论(1) 编辑 收藏 引用 所属分类:
经典排序算法(C/C++实现)