鸡尾酒排序

来源:互联网 发布:古惑仔当年有多火 知乎 编辑:程序博客网 时间:2024/05/16 18:20

鸡尾酒排序(双端冒泡排序)


鸡尾酒排序也叫定向冒泡排序,搅拌排序等,是冒泡排序的一种变形。鸡尾酒排序是在两端开始排序的,而冒泡排序时在一端进行的。


鸡尾酒排序的C++实现:

 


/**************************** *Name:鸡尾酒排序.cpp(双端冒泡排序) *Tags:排序 *Note: *****************************/ #include<iostream>#defineMAX_SIZE 1000usingnamespace std; intCocktailSort(int *, int, int); intmain(){      int nums[MAX_SIZE];      int i, len;      cout << "Input the number ofthe numbers: ";      cin >> len;      for(i = 0; i < len; i++) {            cin >> nums[i];      }      CocktailSort(nums, 0, len); //鸡尾酒排序      cout << "The result of thesort process is :" << endl;      for(i = 0; i < len; i++) {            cout << nums[i] << " ";      }      cout << endl;      return 0;} intCocktailSort(int *nums, int start, int end){      int i, isswap, temp;      isswap = 1;      while(isswap) {            isswap = 0;            for(i = start; i < end-1; i++) {                     if(nums[i] > nums[i+1]) {                            isswap = 1;                            temp = nums[i];                            nums[i] = nums[i+1];                            nums[i+1] = temp;                     }            } //从前向后排序            if(!isswap) { //表明从前向后排序没有可交换的,已有序                     break;            }            for(i = end-1; i > 0; i--) {                     if(nums[i] < nums[i-1]) {                            temp = nums[i];                            nums[i] = nums[i-1];                            nums[i-1]= temp;                            isswap = 1;                     }            } //从后向前排序      }      return 0;}


鸡尾酒排序的时间复杂度也是O(n^2),但是当待排序的数已经基本有序的时候,它的时间复杂度可以就近O(n)。因为如果基本有序,

可能可以在一次从前向后或从后向前的排序后就有序了。

原创粉丝点击