Python Program for Cocktail Sort



What is Cocktail Sort?

Cocktail sort is a variation of bubble sort that sorts the array in both directions on each pass. It is also known as Bidirectional Bubble Sort or Shaker Sort. The algorithm works by traversing the list forward and backward, alternatively, pushing the largest and smallest elements to their respective ends.

This approach helps in reducing the number of iterations compared to Bubble Sort, especially when smaller elements are at the end of the list.

Problem Statement

You are given an unsorted list of elements. The goal is to sort the list using Cocktail Sort, which moves through the list in both directions on each pass to bring the minimum and maximum elements toward their correct positions.

Implementation of Cocktail Sort (Bidirectional Bubble Sort)

Cocktail Sort is also called Bidirectional Bubble Sort. It improves the normal Bubble Sort by sorting the list in both directions during each pass.

  • Forward pass: It moves the largest element to the end.
  • Backward pass: It moves the smallest element to the beginning.

This process continues until no swaps are needed in both passes.

Python Program for Cocktail Sort

In this example, we use a flag to track if any swaps were made. If no swaps are made in a complete cycle (forward and backward), the array is considered sorted.

# Function to perform Cocktail Sort
def cocktail_sort(arr):
   n = len(arr)
   start = 0
   end = n - 1
   swapped = True

   while swapped:
      swapped = False

      # Forward pass
      for i in range(start, end):
         if arr[i] > arr[i + 1]:
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            swapped = True

      if not swapped:
         break

      swapped = False
      end -= 1

      # Backward pass
      for i in range(end - 1, start - 1, -1):
         if arr[i] > arr[i + 1]:
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            swapped = True

      start += 1

   return arr

# Test input
arr = [5, 3, 1, 4, 2]
sorted_arr = cocktail_sort(arr)
print(sorted_arr)

Following is the output obtained -

[1, 2, 3, 4, 5]

The largest and smallest elements are placed at correct positions in each forward and backward pass.

Updated on: 2025-06-13T18:41:55+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements