C++ Program for Cocktail Sort?


The Cocktail sort is another variation of bubble sort. In the bubble sort technique, it always searches from left to right, and finds the largest element at the end, in the second phase it finds the second largest element at the second last position. This sorting technique traverses in both directions alternatively. Let us see the algorithm to understand the idea.

Algorithm

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

Example

 Live Demo

#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] << " ";
   }
}

Output

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

Updated on: 30-Jul-2019

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements