algorithm-in-python/sort/shellSort.py

38 lines
934 B
Python
Raw Normal View History

2018-07-08 23:28:29 +08:00
''' mbinary
#########################################################################
# File : shellSort.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-07-08 23:28:29 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-07-06 16:30
# Description:
#########################################################################
'''
2020-04-15 12:28:20 +08:00
def shellSort(s, gaps=None):
if gaps is None:
2020-04-15 12:28:20 +08:00
gaps = [127, 63, 31, 15, 7, 3, 1]
n = len(s)
for gap in gaps:
2020-04-15 12:28:20 +08:00
for j in range(gap, n):
2018-07-08 16:41:55 +08:00
cur = j
num = s[j]
2020-04-15 12:28:20 +08:00
while cur >= gap and num < s[cur-gap]:
s[cur] = s[cur-gap]
2020-04-15 12:28:20 +08:00
cur -= gap
s[cur] = num
2018-07-08 16:41:55 +08:00
return s
2020-04-15 12:28:20 +08:00
if __name__ == '__main__':
from random import randint
import sys
n = 20
2020-04-15 12:28:20 +08:00
if len(sys.argv) > 1:
n = int(sys.argv[1])
2020-04-15 12:28:20 +08:00
nums = [randint(1, 100) for i in range(n)]
print(nums)
print(shellSort(nums))