Python Program for 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.

How Cocktail Sort Works

Cocktail Sort improves upon Bubble Sort by sorting in both directions during each pass ?

  • Forward pass: Moves the largest element to the end
  • Backward pass: Moves the smallest element to the beginning

This process continues until no swaps are needed in both passes, indicating the array is sorted.

Cocktail Sort Process Initial: 5 3 1 4 2 Forward Pass After Forward: 3 1 4 2 5 Backward Pass After Backward: 1 3 4 2 5 Legend: Sorted position Being processed

Python Implementation

Here's the implementation using a flag to track if any swaps were made. If no swaps occur in a complete cycle, the array is sorted ?

def cocktail_sort(arr):
    n = len(arr)
    start = 0
    end = n - 1
    swapped = True

    while swapped:
        swapped = False

        # Forward pass - move largest to end
        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 - move smallest to start
        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 the algorithm
numbers = [5, 3, 1, 4, 2]
print("Original array:", numbers)
sorted_numbers = cocktail_sort(numbers.copy())
print("Sorted array:", sorted_numbers)
Original array: [5, 3, 1, 4, 2]
Sorted array: [1, 2, 3, 4, 5]

Step-by-Step Execution

Let's trace through the algorithm with the array [5, 3, 1, 4, 2] ?

def cocktail_sort_with_trace(arr):
    n = len(arr)
    start = 0
    end = n - 1
    swapped = True
    pass_count = 1

    print(f"Initial array: {arr}")
    
    while swapped:
        swapped = False
        print(f"\nPass {pass_count}:")

        # Forward pass
        print("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
                print(f"  Swapped {arr[i+1]} and {arr[i]}: {arr}")

        if not swapped:
            break

        swapped = False
        end -= 1

        # Backward pass
        print("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
                print(f"  Swapped {arr[i+1]} and {arr[i]}: {arr}")

        start += 1
        pass_count += 1

    print(f"\nFinal sorted array: {arr}")
    return arr

# Trace execution
numbers = [5, 3, 1, 4, 2]
cocktail_sort_with_trace(numbers)
Initial array: [5, 3, 1, 4, 2]

Pass 1:
Forward pass:
  Swapped 5 and 3: [3, 5, 1, 4, 2]
  Swapped 5 and 1: [3, 1, 5, 4, 2]
  Swapped 5 and 4: [3, 1, 4, 5, 2]
  Swapped 5 and 2: [3, 1, 4, 2, 5]
Backward pass:
  Swapped 4 and 2: [3, 1, 2, 4, 5]
  Swapped 3 and 1: [1, 3, 2, 4, 5]

Pass 2:
Forward pass:
  Swapped 3 and 2: [1, 2, 3, 4, 5]
Backward pass:

Final sorted array: [1, 2, 3, 4, 5]

Time and Space Complexity

Scenario Time Complexity Space Complexity
Best Case O(n) O(1)
Average Case O(n²) O(1)
Worst Case O(n²) O(1)

Advantages and Disadvantages

Advantages:

  • Performs better than bubble sort when smaller elements are at the end
  • In-place sorting algorithm (constant space complexity)
  • Stable sorting algorithm (maintains relative order of equal elements)

Disadvantages:

  • Still has O(n²) worst-case time complexity
  • Not suitable for large datasets
  • More complex implementation than bubble sort

Conclusion

Cocktail Sort is an improvement over Bubble Sort that reduces the number of passes by sorting in both directions. While it has the same worst-case complexity as Bubble Sort, it performs better in practice when smaller elements are positioned at the end of the array.

Updated on: 2026-03-25T06:50:12+05:30

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements