forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cocktail_sort.py
56 lines (44 loc) · 1.37 KB
/
cocktail_sort.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Cocktail sort in python
def cocktailSort(arr):
isSwapped = True
First = 0
Last = len(arr)-1
while isSwapped is True:
# reset isSwapped so that we can use it for this iteration
isSwapped = False
# traversing from first to last element
for i in range(First, Last):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSwapped = True
# if array is already sorted, break the loop
if isSwapped is False:
break
isSwapped = False
# last element is largest so we'll reduce last by one position.
Last = Last-1
# iteration from last to first element
for i in range(Last-1, First-1, -1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
isSwapped = True
# first element is smallest so moving a first one position ahead
First = First+1
# number of elements
n = int(input("Enter number of elements : "))
arr = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
cocktailSort(arr)
print("Sorted array is: ")
print(arr)
'''output:
Time complexity: O(n*n)
Space: O(1)
Enter number of elements : 5
Enter the numbers : 12 4 5 34 2
Sorted array is:
[2, 4, 5, 12, 34]
Enter number of elements : 3
Enter the numbers : 20 14 34
Sorted array is:
[14, 20, 34]
'''