Skip to content

Commit 61763b5

Browse files
author
Manish Kumar
committed
Sorting- Cocktail and Comb
1 parent 78190b0 commit 61763b5

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#Cocktail Sort by Master-Fury
2+
#Worst and Average Case Time Complexity: O(n*n)
3+
#Best Case Time Complexity: O(n)
4+
5+
def Cocktail_Sort(arr): #Cocktail Sort Function
6+
l=len(arr)
7+
swapped= True
8+
start=0
9+
end=l-1
10+
while(swapped == True):
11+
swapped=False
12+
for i in range(start,end): #Forward loop
13+
if(arr[i]>arr[i+1]):
14+
arr[i],arr[i+1]=arr[i+1],arr[i]
15+
swapped= True
16+
if(swapped==False):
17+
break
18+
swapped = False
19+
end=end-1
20+
for i in range (end-1,start-1,-1): #Backward Loop
21+
if(arr[i]>arr[i+1]):
22+
arr[i],arr[i+1]=arr[i+1],arr[i]
23+
swapped= True
24+
start=start+1
25+
26+
#Driver Code
27+
28+
arr=[2,5,21,431,4,53,22,144,123,8] #Your array
29+
Cocktail_Sort(arr)
30+
print("Sorted array: ",arr)
31+
32+
33+
##Description
34+
##Cocktail Sort is a variation of Bubble sort.
35+
##The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct
36+
##position in first iteration and second largest in second iteration and so on.
37+
##Cocktail Sort traverses through a given array in both directions alternatively.
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#Comb Sort by Master-Fury
2+
#Time Complexity : Worst case complexity of this algorithm is O(n^2).
3+
#Best Case complexity is O(n).
4+
5+
#DESCRIPTION
6+
##Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values.
7+
##So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1.
8+
##The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1.
9+
##Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bublle Sort.
10+
##The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]
11+
12+
13+
def new_gap(gap): #Function to find the gap(or range)
14+
gap=(gap*10)//13
15+
if(gap<1):
16+
return 1
17+
return gap
18+
19+
def Comb_Sort(arr): #Comb Sort Function
20+
n=len(arr)
21+
gap=n
22+
swapped = True
23+
while gap!=1 or swapped == 1:
24+
gap=new_gap(gap)
25+
swapped=False
26+
for i in range(0,n-gap):
27+
if (arr[i]>arr[i+gap]):
28+
arr[i],arr[i+gap]=arr[i+gap],arr[i]
29+
swapped =True
30+
#Driver Code
31+
32+
arr=[2,85,443,7,8,3,67,3,89,0] #Your array
33+
Comb_Sort(arr)
34+
print ("Sorted array: ",arr)

0 commit comments

Comments
 (0)