Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 36003d1

Browse files
authored
Added Cocktail Sort Algorithm in Python (#553)
1 parent a9a1ed9 commit 36003d1

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Title - Cocktail Shaker Sort Algorithm
3+
Pupose - Sorts a given array in ascending order.
4+
Time Complexity - O(n^2)
5+
"""
6+
import random
7+
8+
9+
class CocktailSort:
10+
""" CocktailSort Algorithm Implementation
11+
12+
arr: an unordered list
13+
output: return list in ascending order
14+
15+
Example:
16+
>>> sort = CocktailSort()
17+
Cocktail Sort Algorithm is Initialized.
18+
>>> sort([4, 2, 4, 6, 1, 5])
19+
[1, 2, 4, 4, 5, 6]
20+
21+
"""
22+
23+
def __init__(self):
24+
print("Cocktail Sort Algorithm is Initialized.")
25+
26+
def __call__(self, arr):
27+
left_bound = 0
28+
right_bound = len(arr) - 1
29+
did_swap = True
30+
while did_swap:
31+
did_swap = False
32+
33+
for i in range(left_bound, right_bound):
34+
if arr[i + 1] < arr[i]:
35+
arr[i + 1], arr[i] = arr[i], arr[i + 1]
36+
did_swap = True
37+
38+
if not did_swap:
39+
break
40+
41+
right_bound -= 1
42+
43+
for i in range(right_bound - 1, left_bound - 1, -1):
44+
if arr[i + 1] < arr[i]:
45+
arr[i + 1], arr[i] = arr[i], arr[i + 1]
46+
47+
left_bound += 1
48+
49+
return arr
50+
51+
52+
sort = CocktailSort()
53+
print(sort([5, 2, 1, 6, 10])) # beginning example
54+
55+
# more populated examples
56+
print(sort(random.sample(range(1, 101), 50)))
57+
print(sort(random.sample(range(1, 201), 100)))

0 commit comments

Comments
 (0)