Skip to content

Commit 655d0a3

Browse files
committed
Added cocktail_shaker_sort to python
1 parent 054809e commit 655d0a3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/python/Cocktail_Shaker_Sort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def cocktail_shaker_sort(arr):
2+
n = len(arr)
3+
swapped = True
4+
start = 0
5+
end = n - 1
6+
7+
while swapped:
8+
# reset the swapped flag on entering the loop
9+
swapped = False
10+
11+
# Traverse the list from left to right
12+
for i in range(start, end):
13+
if arr[i] > arr[i + 1]:
14+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
15+
swapped = True
16+
17+
# If no elements were swapped, the list is already sorted
18+
if not swapped:
19+
break
20+
21+
# Reset the swapped flag for the next stage
22+
swapped = False
23+
24+
# Move the end point back by one
25+
end -= 1
26+
27+
# Traverse the list from right to left
28+
for i in range(end - 1, start - 1, -1):
29+
if arr[i] > arr[i + 1]:
30+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
31+
swapped = True
32+
33+
# Move the start point forward by one
34+
start += 1
35+
36+
# Example usage
37+
arr = [5, 1, 4, 2, 8, 0, 2]
38+
cocktail_shaker_sort(arr)
39+
print("Sorted array:", arr)

0 commit comments

Comments
 (0)