forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcocktail_sort.py
More file actions
41 lines (33 loc) · 1.03 KB
/
Copy pathcocktail_sort.py
File metadata and controls
41 lines (33 loc) · 1.03 KB
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
40
41
"""
cocktail_sort.py
Implementation of cocktail sort (aka bidirectional bubble sort,
or the happy hour sort) on a list.
Cocktail Sort Overview:
------------------------
Walk the list bidirectionally, swapping neighbors if one should come
before/after the other.
Time Complexity: O(n**2)
Space Complexity: O(1) Auxiliary
Stable: Yes
Psuedo Code: http://en.wikipedia.org/wiki/Cocktail_sort
"""
def sort(seq):
lower_bound = -1
upper_bound = len(seq) - 1
swapped = True
while swapped:
swapped = False
lower_bound += 1
for i in range(lower_bound, upper_bound):
if seq[i] > seq[i + 1]:
seq[i], seq[i + 1] = seq[i + 1], seq[i]
swapped = True
if not swapped:
break
swapped = False
upper_bound -= 1
for i in range(upper_bound, lower_bound, -1):
if seq[i] < seq[i - 1]:
seq[i], seq[i - 1] = seq[i - 1], seq[i]
swapped = True
return seq