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
- 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.
- 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.
- Repeat: Continue both passes alternately until no swaps are needed.
Python Implementation
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:
- n = len(a): Stores the total number of elements in the list.
- swapped = True: Used as a flag to track if any swap occurs.
- Forward pass (for i in range(start, end):): Compares adjacent elements and swaps if out of order.
- if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i]: Moves the largest element to the right end.
- if (swapped == False): break: Stops when no swaps occur, meaning the array is sorted.
- Backward pass (for i in range(end - 1, start - 1, -1):): Moves the smallest element to the left end.
- if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i]: Performs reverse swapping.