时间复杂度是程序运行的时间,也可以说是次数;
空间复杂度是程序占用的空间;
5.希尔排序


#!/usr/bin/python
# coding: utf8
def insert_sort(l, start, increment):
for i in range(start+increment, len(l), increment):
# print i, l[i]
for j in range(start, len(l[:i]), increment):
# print j, '---'
if l[j] > l[i]:
l[i], l[j] = l[j], l[i]
print increment, '--',l
return l
def ShellSort(l, increment):
# 依次进行分层
while increment:
# 每一层,都进行n次插入排序
for i in range(0, increment):
insert_sort(l, i, increment)
increment -= 1
return l
if __name__ == "__main__":
l = [5, 2, 9, 8, 1, 10, 3, 4, 7]
increment = len(l)/3+1 if len(l)%3 else len(l)/3
print "开始", l
l = ShellSort(l, increment)
print "结束", l
结果:
开始 [5, 2, 9, 8, 1, 10, 3, 4, 7]
3 -- [3, 2, 9, 5, 1, 10, 8, 4, 7]
3 -- [3, 1, 9, 5, 2, 10, 8, 4, 7]
3 -- [3, 1, 7, 5, 2, 9, 8, 4, 10]
2 -- [2, 1, 3, 5, 7, 9, 8, 4, 10]
2 -- [2, 1, 3, 4, 7, 5, 8, 9, 10]
1 -- [1, 2, 3, 4, 5, 7, 8, 9, 10]
结束 [1, 2, 3, 4, 5, 7, 8, 9, 10]
[Finished in 0.0s]