From 655d0a32815efc90e764d5ce4a5371c188ed8138 Mon Sep 17 00:00:00 2001 From: akshayram1 Date: Fri, 4 Oct 2024 20:56:24 +0530 Subject: [PATCH] Added cocktail_shaker_sort to python --- src/python/Cocktail_Shaker_Sort.py | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/python/Cocktail_Shaker_Sort.py diff --git a/src/python/Cocktail_Shaker_Sort.py b/src/python/Cocktail_Shaker_Sort.py new file mode 100644 index 00000000..232bd441 --- /dev/null +++ b/src/python/Cocktail_Shaker_Sort.py @@ -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)