 # C Programming Code Examples

## C > Sorting Searching Code Examples

### C Program to Implement CockTail Sort

``` C Program to Implement CockTail Sort This C Program implements cocktail sort. Cocktail 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 only marginally more difficult to implement than a bubble sort, and solves the problem of turtles in bubble sorts. The various names of cocktail sort are bidirectional bubble sort, cocktail shaker sort, shaker sort , ripple sort, shuffle sort, shuttle sort or happy hour sort #include <stdio.h> #define MAX 8 int main() { int data[MAX]; int x, j, n, c; printf("\nEnter the data"); for (x = 0; x < MAX; x++) { scanf("%d", &data[x]); } n = MAX; do { /* Rightward pass will shift the largest element to its correct place at the end */ for (x = 0; x < n - 1; x++) { if (data[x] > data[x + 1]) { data[x] = data[x] + data[x + 1]; data[x + 1] = data[x] - data[x + 1]; data[x] = data[x] - data[x + 1]; } } n = n - 1; /* Leftward pass will shift the smallest element to its correct place at the beginning */ for (x= MAX - 1, c = 0; x >= c; x--) { if(data[x] < data[x - 1]) { data[x] = data[x] + data[x - 1]; data[x - 1] = data[x] - data[x - 1]; data[x] = data[x] - data[x - 1]; } } c = c + 1; } while (n != 0 && c != 0); printf("The sorted elements are:"); for (x = 0; x < MAX; x++) { printf("%d\t", data[x]); } } ``` 