前面我们详细讲解了希尔排序算法,现在我们直接上python代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
#希尔排序
def shell_sort(the_list):
d_value = len(the_list)/2
while d_value > 0:
for i in range(len(the_list)):
j = i
while (j-d_value >= 0) and (the_list[j] < the_list[j-d_value]):
the_list[j], the_list[j - d_value] = the_list[j-d_value], the_list[j]
j -= d_value
i += 1
d_value /= 2
return the_list
if __name__ == '__main__':
the_list = [10, 12, 7, 5]
print "排序前:" + str(the_list)
print "排序后:" + str(shell_sort(the_list))
我们运行一下,看看结果
排序前:[10, 12, 7, 5]
排序后:[5, 7, 10, 12]
符合预期
本文详细介绍了一种有效的排序算法——希尔排序,并提供了完整的Python代码实现。通过逐步分解算法过程,展示了希尔排序如何通过增量序列逐步排序数组,最终实现高效的数据排序。
234

被折叠的 条评论
为什么被折叠?



