Cocktail sort, 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, or shuttle 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. Its time complexity is O(n2).
Here is the source code of the C program to sort integers using Shaker Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void shakersort(int a[], int n)
{
int p, i;
for (p = 1; p <= n / 2; p++)
{
for (i = p - 1; i < n - p; i++)
if (a[i] > a[i+1])
swap(&a[i], &a[i + 1]);
for (i = n - p - 1; i >= p; i--)
if (a[i] < a[i-1])
swap(&a[i], &a[i - 1]);
}
}
int main()
{
int arr[10] = {43, 432, 36, 5, 6, 57, 94, 63, 3, 44};
int i;
shakersort(arr, 10);
for (i = 0 ; i < 10; i++)
printf("%d ", arr[i]);
return 0;
}
$ gcc shakersort.c -o shakersort $ ./shakersort Sorted array is : 3 5 6 36 43 44 57 63 94 432
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
If you find any mistake above, kindly email to [email protected]- Check Computer Science Books
- Apply for C Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship