鸡尾酒排序 C++ 程序?


鸡尾酒排序是冒泡排序的另一种变体。在冒泡排序技术中,它总是从左到右进行搜索,在最后找到最大元素,在第二阶段在倒数第二个位置找到第二大元素。这种排序技术交替地朝两个方向遍历。让我们看看该算法来理解这个想法。

算法

cocktail(array, n)

Begin
   flag := true
   start := 0, end := n-1
   while flag is set, do
      flag := false
      for i in range start to end-1, do
         if arr[i] > arr[i+1], then
            exchange arr[i] and arr[i+1]
            flag := true
         end if
      done
      if flag is not set, then
         break
      end if
      flag := false
      end := end – 1
      for i in range end -1 down to start, do
         if arr[i] > arr[i+1], then
            exchange arr[i] and arr[i+1]
            flag := true
         end if
      done
      start := start + 1
   done
End

示例

 实时演示

#include<iostream>
using namespace std;
void cocktailSort(int arr[], int n){
   bool flag = true;
   int start = 0, end = n-1;
   while(flag){
      flag = false;
      for(int i = start; i<end; i++){ //scan from left to right as bubble sort
         if(arr[i] > arr[i+1]){
            swap(arr[i], arr[i+1]);
            flag = true;
         }
      }
      if(!flag){ //if nothing has changed simply break the loop
         break;
      }
      flag = false;
      end--; //decrease the end pointer
      for(int i = end - 1; i >= start; i--){ //scan from right to left
         if(arr[i] > arr[i+1]){
            swap(arr[i], arr[i+1]);
            flag = true;
         }
      }
      start++;
   }
}
main() {
   int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   cocktailSort(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Sorted Sequence 13 20 32 35 40 54 74 98 98 154

更新于: 30-Jul-2019

525 次查看

开启你的职业生涯

完成课程,获得认证

开始吧
广告