鸡尾酒排序
来源:互联网 发布:大数据报告 编辑:程序博客网 时间:2024/04/28 01:57
鸡尾酒排序其实就是双向冒泡排序,它是冒泡排序的一种变形。
冒泡排序是不断往一个方法冒泡,鸡尾酒排序则是先向一个方向,然后向另一个方向,来回冒泡。
不多废话了,直接上代码:
/* cocktail_sort * Principle: bidirection bubble sort. * swap the biggest element to the last, * then swap the smallest element to the first, * ans so on and so on. */ #include <stdio.h>#include <stdlib.h> #define SIZE_ARRAY_1 5#define SIZE_ARRAY_2 6#define SIZE_ARRAY_3 20void cocktail_sort(int a[], int n);void showArray(int a[], int n);int main(){int array1[SIZE_ARRAY_1]={1,4,2,-9,0};int array2[SIZE_ARRAY_2]={10,5,2,1,9,2};int array3[SIZE_ARRAY_3];for(int i=0; i<SIZE_ARRAY_3; i++){array3[i] = (int)((40.0*rand())/(RAND_MAX+1.0)-20);}printf("Before sort, ");showArray(array1, SIZE_ARRAY_1);cocktail_sort(array1, SIZE_ARRAY_1);printf("After sort, ");showArray(array1, SIZE_ARRAY_1);printf("Before sort, ");showArray(array2, SIZE_ARRAY_2);cocktail_sort(array2, SIZE_ARRAY_2);printf("After sort, ");showArray(array2, SIZE_ARRAY_2);printf("Before sort, ");showArray(array3, SIZE_ARRAY_3);cocktail_sort(array3, SIZE_ARRAY_3);printf("After sort, ");showArray(array3, SIZE_ARRAY_3);return 0;}void showArray(int a[], int n){if(n>0)printf("This array has %d items: ", n);elseprintf("Error: array size should bigger than zero.\n");for(int i=0; i<n; i++){printf("%d ", a[i]);}printf("\n");}void swap(int &a, int &b){int tmp=a;a = b;b = tmp;}void cocktail_sort(int a[], int n){int i;int begin=0;int end=n-1;while(begin<end) {// swap the largest to the endfor(int i=begin; i<end; i++) {if(a[i]>a[i+1]) swap(a[i], a[i+1]);}end--;// swap the smallest to the beginningfor(int i=end; i>begin; i--) {if(a[i]<a[i-1]) swap(a[i], a[i-1]);}begin++;}}
0 0
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- 鸡尾酒排序
- mysql格式化时间戳
- PHPExcel
- Mysql事件学习
- 教育的美好姿态
- 《将博客搬至CSDN》
- 鸡尾酒排序
- 活用UML-软件设计高手(广州 2014年6月14-15日)
- GCC常用命令
- 关于HttpClient的总结
- js给onclick赋值,传参数
- 折腾paramiko
- 【Error】Python:SyntaxError: Non-ASCII character '\xe5'解决方法
- 指称语义简介
- android 只允许运行一个Activity实例