# C program to implement cocktail sort algorithm

Here, we are going to learn how to implement cocktail sort algorithm using C program?
Submitted by Nidhi, on August 16, 2021

Problem Solution:

Here, we will create an array of integers then we will read array elements from the user and implement the cocktail sort algorithm to arrange array elements in ascending order.

Program:

The source code to implement the cocktail sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to implement cocktail sort algorithm

#include <stdio.h>

#define MAX 8

void CockTailSort(int* arr)
{
int n = MAX;
int i = 0;
int c = 0;

do {
i = 0;
while (i < n - 1) {
if (arr[i] > arr[i + 1]) {
arr[i] = arr[i] + arr[i + 1];
arr[i + 1] = arr[i] - arr[i + 1];
arr[i] = arr[i] - arr[i + 1];
}
i++;
}

n = n - 1;
i = MAX - 1;
c = 0;

while (i >= c) {
if (arr[i] < arr[i - 1]) {
arr[i] = arr[i] + arr[i - 1];
arr[i - 1] = arr[i] - arr[i - 1];
arr[i] = arr[i] - arr[i - 1];
}
i--;
}
c = c + 1;
} while (n != 0 && c != 0);
}

int main()
{
int arr[MAX];
int i = 0;

printf("Enter array elements:\n");
while (i < MAX) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}

CockTailSort(arr);

printf("Sorted Array: \n");
i = 0;
while (i < MAX) {
printf("%d ", arr[i]);
i++;
}
printf("\n");

return 0;
}
```

Output:

```RUN 1:
Enter array elements:
Element[0]: 34
Element[1]: 23
Element[2]: 13
Element[3]: 56
Element[4]: 63
Element[5]: 34
Element[6]: 56
Element[7]: 76
Sorted Array:
13 23 34 34 56 56 63 76

RUN 2:
Enter array elements:
Element[0]: 12
Element[1]: 23
Element[2]: 45
Element[3]: 1
Element[4]: 2
Element[5]: 7
Element[6]: 89
Element[7]: 12
Sorted Array:
2 7 8 12 12 23 45 89
```

Explanation:

Here, we created two functions CockTailSort() and main().The CockTailSort() function is used to arrange array element in ascending order.

In the main() function, we created an array of integers arr. Then we sorted the elements of the array using the CockTailSort() function and printed the sorted array on the console screen.

Top MCQs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates