C Program to Implement Shaker Sort

This C program sorts a given array of integer numbers using Shaker Sort technique.

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.

  1. #include <stdio.h>
  2. void swap(int *a, int *b){
  3.     int temp;
  4.     temp = *a;
  5.     *a = *b;
  6.     *b = temp;
  7. }
  8. void shakersort(int a[], int n)
  9. {
  10.     int p, i;
  11.     for (p = 1; p <= n / 2; p++)
  12.     {
  13.         for (i = p - 1; i < n - p; i++)
  14.             if (a[i] > a[i+1])
  15.                 swap(&a[i], &a[i + 1]);
  16.         for (i = n - p - 1; i >= p; i--)
  17.             if (a[i] < a[i-1])
  18.                 swap(&a[i], &a[i - 1]);
  19.     }
  20. }
  21. int main()
  22. {
  23.     int arr[10] = {43, 432, 36, 5, 6, 57, 94, 63, 3, 44};
  24.     int i;
  25.     shakersort(arr, 10);
  26.     for (i = 0 ; i < 10; i++)
  27.         printf("%d ", arr[i]);
  28.     return 0;
  29. }

$ 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.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.