C program for Cocktail Sort Algorithm : Cocktail sort is also known as** bidirectional bubble sort**, **cocktail shaker sort**, **shaker sort** (which can also refer to a variant of selection sort), **ripple sort**, **shuffle sort**, **shuttle sort** or** happy hour sort**, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is marginally more difficult to implement in C than a bubble sort.

**Difference between Cocktail Sort Algorithm and Bubble Sort Algorithm** :

The difference between cocktail sort and bubble sort is that instead of repeatedly passing through the list from bottom to top, it passes alternately from bottom to top and then from top to bottom. The result is that it has a slightly better performance than bubble sort, because it sorts in both directions. (Bubble sort can only move items backwards one step per iteration.)

Normally** cocktail sort or shaker sort pass** (one time in both directions) is counted as two bubble sort passes. In a typical implementation the cocktail sort is less than two times faster than a bubble sort implementation.

Let us see C how to write a **C program** for Cocktail sort which accepts **numbers** as input and generates the output sorted list.

**C program for Cocktail Sort Algorithm** :

#include<stdio.h> #include<conio.h> #define MAX 10 int main() { int a[MAX],b[MAX]; int n,i,j,pass,sw=1,temp; printf("Enter the number of elements present.\n"); scanf("%d",&n); printf("Enter the elements :\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); b[i]=a[i]; } printf("The array elements before sorting are\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\nElements after Cocktail sort are\n"); sw=1; for(i=0;i<n-1 && sw==1;i++) { sw=0; for(j=0;j<n-1-i;j++) { if(b[j]>b[j+1]) { temp=b[j+1]; b[j+1]=b[j]; b[j]=temp; sw=1; } if(b[n-1-j]<b[n-2-j]) { temp=b[n-2-j]; b[n-2-j]=b[n-1-j]; b[n-1-j]=temp; sw=1; } } } for(j=0;j<n;j++) printf("%d\t",b[j]); printf("\n\n\n\tNo. of passes : %d\n",i); printf("\n\n******************************************************"); printf("\n*********** Code written by Ccodechamp ***************"); printf("\n******************************************************"); getch(); }

We hope you all have enjoyed the C program for cocktail shaker sort algorithm. If you have any issues with the code let us know in form of comments.

Thanks dude!

Useful information. Lucky me I found your web site by accident, and I am stunned why this twist of fate did not happened in advance! I bookmarked it.

this is a great source web site……the codes are very helpful ….have it in marks…!!