1.for版本--希尔排序
def shell_sort_for(a_list):
'''希尔排序for版本'''
num = len(a_list)
gap = num // 2
# for k in range(gap, 0, gap//2):
while gap > 0:
for j in range(gap, num):
for i in range(j, 0, -gap):
if a_list[i] < a_list[i-gap]:
a_list[i-gap],a_list[i] = a_list[i],a_list[i-gap]
else:
break
gap //= 2
return a_list
2. while版本--希尔排序
def shell_sort_while(b_list):
'''希尔排序while版本'''
num = len(b_list)
gap = num // 2
while gap > 0:
j = gap
while j < num:
i = j
while i > 0:
if b_list[i] < b_list[i-gap]:
b_list[i-gap],b_list[i] = b_list[i],b_list[i-gap]
i -= gap
else:
break
j += 1
gap //= 2
return b_list
3. 测试用例
if __name__ == '__main__':
a_list = [3,4,8,9,1,2]
print(shell_sort_for(a_list))
b_list = [3,4,8,9,1,2]
print(shell_sort_while(b_list))
4. 算法时间复杂度分析
- 最好时间复杂度:O(n1.3)
- 最坏时间复杂度:O(n2)
- 稳定性:不稳定