Python Program for Cocktail Sort (original) (raw)

Last Updated : 7 Nov, 2025

Cocktail Sort is a variation of Bubble Sort that traverses the list in both directions alternately. While Bubble Sort only moves larger elements to the end in each pass, Cocktail Sort also moves smaller elements to the beginning, improving efficiency in partially sorted arrays.

How Cocktail Sort Works

  1. **Forward Pass: Traverse the array from left to right. Swap adjacent elements if the left one is greater than the right. After this pass, the largest element moves to the end.
  2. **Backward Pass: Traverse from right to left. Swap adjacent elements if the right one is smaller. After this pass, the smallest element moves to the beginning.
  3. **Repeat: Continue both passes alternately until no swaps are needed.

Python Implementation

Python `

def cocktailSort(a): n = len(a) swapped = True start = 0 end = n-1 while (swapped==True):

    swapped = False
    for i in range (start, end):
        if (a[i] > a[i+1]) :
            a[i], a[i+1]= a[i+1], a[i]
            swapped=True

    if (swapped==False):
        break
    swapped = False

    end = end-1

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

a = [5, 1, 4, 2, 8, 0, 2] cocktailSort(a) print("Sorted array is:") for i in range(len(a)): print ("%d" %a[i]),

`

Output

Sorted array is: 0 1 2 2 4 5 8

**Explanation: