Skip to content

Commit ec9e83e

Browse files
Create combSort.py
1 parent b89714c commit ec9e83e

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Python/Sorting/combSort.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Python program for implementation of CombSort
2+
3+
# To find next gap from current
4+
def getNextGap(gap):
5+
6+
# Shrink gap by Shrink factor
7+
gap = (gap * 10)/13
8+
if gap < 1:
9+
return 1
10+
return gap
11+
12+
# Function to sort arr[] using Comb Sort
13+
def combSort(arr):
14+
n = len(arr)
15+
16+
# Initialize gap
17+
gap = n
18+
19+
# Initialize swapped as true to make sure that
20+
# loop runs
21+
swapped = True
22+
23+
# Keep running while gap is more than 1 and last
24+
# iteration caused a swap
25+
while gap !=1 or swapped == 1:
26+
27+
# Find next gap
28+
gap = getNextGap(gap)
29+
30+
# Initialize swapped as false so that we can
31+
# check if swap happened or not
32+
swapped = False
33+
34+
# Compare all elements with current gap
35+
for i in range(0, n-gap):
36+
if arr[i] > arr[i + gap]:
37+
arr[i], arr[i + gap]=arr[i + gap], arr[i]
38+
swapped = True
39+
40+
41+
# Driver code to test above
42+
arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]
43+
combSort(arr)
44+
45+
print ("Sorted array:")
46+
for i in range(len(arr)):
47+
print (arr[i]),

0 commit comments

Comments
 (0)