希尔排序的python实现
实现通过数据结构了解了希尔排序的算法,然后在大脑中不断联想希尔排序的动画——每个数字分别都是怎么移动的。
最后苦苦钻研,终于在pycharm强大的调式功能下,写出了希尔排序的python实现。我发现在长时间的思考之下,脑袋的专注力不够用了,我就站起来休息下,听两三分钟纯音乐,然后再投入思考,再回来后反而更加思维清晰。
import mathdef shellsort(array):increment = len(array)while increment > 1: #当型循环increment = int(increment/3) + 1 #设置增量for i in range(len(array)) :#在每一轮的大循环中进行遍历循环j = i + incrementif j < len(array) :#如果j取值超过数组长度,就退出循环temp = array[j] #哨兵while ((j-increment)>=0) and (array[j-increment]>temp):array[j] = array[j-increment]j-=incrementarray[j]=tempelse:breakarray = [84,83,88,87,61,50,70,60,80,99]print('原数组为:'+str(array))shellsort(array)print('希尔排序后:'+str(array))
网上看看别人写的代码如何:
def shellSort(arr):n = len(arr)gap = int(n/2)while gap > 0:for i in range(gap,n):temp = arr[i]j = iwhile j >= gap and arr[j-gap] >temp:arr[j] = arr[j-gap]j -= gaparr[j] = tempgap = int(gap/2)arr = [ 12, 34, 54, 2, 3]n = len(arr) print ("排序前:") for i in range(n):print(arr[i]),shellSort(arr)print ("\n排序后:") for i in range(n):print(arr[i])
下面这段也是别人写的:
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Author : xiaokedef shell_sort(alist):"""希尔排序"""n = len(alist)gap = n // 2while gap >= 1:for j in range(gap, n):i = jwhile (i - gap) >= 0:if alist[i] < alist[i - gap]:alist[i], alist[i - gap] = alist[i - gap], alist[i]i -= gapelse:breakgap //= 2if __name__ == '__main__':alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]print("原列表为:%s" % alist)shell_sort(alist)print("新列表为:%s" % alist)# 结果如下:# 原列表为:[54, 26, 93, 17, 77, 31, 44, 55, 20]# 新列表为:[17, 20, 26, 31, 44, 54, 55, 77, 93]
看看有何区别,并值得在细节上完善自己的理解漏洞。
