-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathCocktail_Shaker_Sort.py
39 lines (31 loc) · 1.01 KB
/
Cocktail_Shaker_Sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def cocktail_shaker_sort(arr):
n = len(arr)
swapped = True
start = 0
end = n - 1
while swapped:
# reset the swapped flag on entering the loop
swapped = False
# Traverse the list from left to right
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 no elements were swapped, the list is already sorted
if not swapped:
break
# Reset the swapped flag for the next stage
swapped = False
# Move the end point back by one
end -= 1
# Traverse the list from right to left
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
# Move the start point forward by one
start += 1
# Example usage
arr = [5, 1, 4, 2, 8, 0, 2]
cocktail_shaker_sort(arr)
print("Sorted array:", arr)