MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / cocktail_shaker_sort

Function cocktail_shaker_sort

sorts/cocktail_shaker_sort.py:8–59  ·  view source on GitHub ↗

Sorts a list using the Cocktail Shaker Sort algorithm. :param arr: List of elements to be sorted. :return: Sorted list. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker

(arr: list[int])

Source from the content-addressed store, hash-verified

6
7
8def cocktail_shaker_sort(arr: list[int]) -> list[int]:
9 """
10 Sorts a list using the Cocktail Shaker Sort algorithm.
11
12 :param arr: List of elements to be sorted.
13 :return: Sorted list.
14
15 >>> cocktail_shaker_sort([4, 5, 2, 1, 2])
16 [1, 2, 2, 4, 5]
17 >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11])
18 [-4, 0, 1, 2, 5, 11]
19 >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2])
20 [-2.4, 0.1, 2.2, 4.4]
21 >>> cocktail_shaker_sort([1, 2, 3, 4, 5])
22 [1, 2, 3, 4, 5]
23 >>> cocktail_shaker_sort([-4, -5, -24, -7, -11])
24 [-24, -11, -7, -5, -4]
25 >>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
26 ['apple', 'banana', 'cherry', 'date', 'elderberry']
27 >>> cocktail_shaker_sort((-4, -5, -24, -7, -11))
28 Traceback (most recent call last):
29 ...
30 TypeError: 'tuple' object does not support item assignment
31 """
32 start, end = 0, len(arr) - 1
33
34 while start < end:
35 swapped = False
36
37 # Pass from left to right
38 for i in range(start, end):
39 if arr[i] > arr[i + 1]:
40 arr[i], arr[i + 1] = arr[i + 1], arr[i]
41 swapped = True
42
43 if not swapped:
44 break
45
46 end -= 1 # Decrease the end pointer after each pass
47
48 # Pass from right to left
49 for i in range(end, start, -1):
50 if arr[i] < arr[i - 1]:
51 arr[i], arr[i - 1] = arr[i - 1], arr[i]
52 swapped = True
53
54 if not swapped:
55 break
56
57 start += 1 # Increase the start pointer after each pass
58
59 return arr
60
61
62if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected