Skip to content

Added cocktail_shaker_sort to python #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/python/Cocktail_Shaker_Sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)
Loading