Python Program for Comb Sort
Last Updated :
09 Sep, 2023
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using a gap of the size of more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus
Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.
Python Program for Comb Sort
The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]
Although it works better than Bubble Sort on average, the worst case remains O(n2).
Python3
def getNextGap(gap):
gap = (gap * 10 ) / 13
if gap < 1 :
return 1
return gap
def combSort(arr):
n = len (arr)
gap = n
swapped = True
while gap ! = 1 or swapped = = 1 :
gap = getNextGap(gap)
swapped = False
for i in range ( 0 , n - gap):
if arr[i] > arr[i + gap]:
arr[i], arr[i + gap] = arr[i + gap], arr[i]
swapped = True
arr = [ 8 , 4 , 1 , 3 , - 44 , 23 , - 6 , 28 , 0 ]
combSort(arr)
print ( "Sorted array:" )
for i in range ( len (arr)):
print (arr[i]),
|
Output
Sorted array:
-44 -6 0 1 3 4 8 23 28
Time Complexity: The worst-case complexity of this algorithm is O(n2).
Auxiliary Space: O(1).
Please refer complete article on Comb Sort for more details!
Share your thoughts in the comments
Please Login to comment...