用于梳状排序的Python程序
梳状排序主要是对冒泡排序的改进。冒泡排序总是比较相邻的值。所以所有的反转都被一一删除。梳排序通过使用大于 1 的间隙来改进冒泡排序。间隙从一个较大的值开始,并在每次迭代中缩小 1.3 倍,直到达到值 1。因此,梳排序用一个来删除多个反转计数交换并且比冒泡排序执行得更好。
根据经验发现收缩因子为 1.3(通过在超过 200,000 个随机列表上测试 Combsort)[来源:Wiki]
虽然平均而言它比冒泡排序效果更好,但最坏的情况仍然是 O(n 2 )。
Python
# Python program for implementation of CombSort
# To find next gap from current
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10)/13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
n = len(arr)
# Initialize gap
gap = n
# Initialize swapped as true to make sure that
# loop runs
swapped = True
# Keep running while gap is more than 1 and last
# iteration caused a swap
while gap !=1 or swapped == 1:
# Find next gap
gap = getNextGap(gap)
# Initialize swapped as false so that we can
# check if swap happened or not
swapped = False
# Compare all elements with current gap
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
# Driver code to test above
arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]
combSort(arr)
print ("Sorted array:")
for i in range(len(arr)):
print (arr[i]),
# This code is contributed by Mohit Kumra
输出 :
Sorted array:
-44 -6 0 1 3 4 8 23 28 56
请参阅完整的梳状排序文章了解更多详情!