鸡尾酒排序(改进的冒泡排序)
4125 点击·0 回帖
![]() | ![]() | |
![]() | 经典排序算法-鸡尾酒排序CocktailSort 鸡尾酒排序(改进的冒泡排序),原理是对要排序的数组进行双向冒泡排序,双向冒泡排序又称为鸡尾酒排序。 其示例代码如下: #include <iosTREAM> using namespace std; /**/////////鸡尾酒排序/双向冒泡排序(改进的冒泡排序) void CocktailSort(int *a,int nsize) { int tail=nsize-1; for (int i=0;i<tail;) { for (int j=tail;j>i;--j) //第一轮,先将最小的数据排到前面 { if (a[j]<a[j-1]) { int temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; } } ++i; //原来i处数据已排好序,加1 for (j=i;j<tail;++j) //第二轮,将最大的数据排到后面 { if (a[j]>a[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } tail--; //原tail处数据也已排好序,将其减1 } } void OutPut(int *b,int nLength) { for (int i=0;i<nLength;i++) { cout<<b<<'\t'; } cout<<endl; } int main() { int nData[]={1,4,2,5,67,86,24,63,676,23,1,3,2,34}; CocktailSort(nData,sizeof(nData)/sizeof(nData[0])); OutPut(nData,sizeof(nData)/sizeof(nData[0])); return 1; } 摘自 CodeBeauty | |
![]() | ![]() |