Javatpoint Logo
Javatpoint Logo

Cocktail Sort

Cocktail sort is the variation of Bubble Sort which traverses the list in both directions alternatively. It is different from bubble sort in the sense that, bubble sort traverses the list in forward direction only, while this algorithm traverses in forward as well as backward direction in one iteration.

Algorithm

In cocktail sort, one iteration consists of two stages:

  1. The first stage loop through the array like bubble sort from left to right. The adjacent elements are compared and if left element is greater than the right element, then we swap those elements. The largest element of the list is placed at the end of the array in the forward pass.
  2. The second stage loop through the array from the right most unsorted element to the left. The adjacent elements are compared and if right element is smaller than the left element then, we swap those elements. The smallest element of the list is placed at the beginning of the array in backward pass.

The process continues until the list becomes unsorted.

Example

Consider the array A : {8, 2, 3, 1, 9}. Sort the elements of the array using Cocktail sort.

Iteration 1:

Forward pass :

At the end of first forward pass: the largest element of the list is placed at the end.

Backward pass:

At the end of first backward pass; the smallest element has been placed at the first index of the array.

If we have a look at the list produced in the first step; we can find that the list has already been sorted in ascending order but the algorithm will process itself completely.

Complexity

Complexity Best Case Average Case Worst Case
Time Complexity O(n2) O(n2) O(n2)
Space Complexity O(1)

C Program

Output:

printing sorted array :
0 1 2 3 8 10 23 45 

C++ Program

Output:

printing sorted array :
0 1 2 3 8 10 23 45

Java Program

Output:

printing sorted array :

0 1 2 3 8 10 23 45

C# Program

Output:

printing sorted array :

0 1 2 3 8 10 23 45

Python Program

Output:

printing sorted array :

0 1 2 3 8 10 23 45

Rust Program

Output:

printing sorted array :
0 1 2 3 8 10 23 45

JavaScript Program

Output:

printing sorted array :
0
1 2 3 8 10 23 45

Next TopicCycle Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA