【学习笔记】python版希尔排序及其时间复杂度分析

希尔排序是插入排序的一个变种,插入排序是比较步长为1,而希尔排序的比较步长则不只是1,通常情况下是一个数组,数组不同则时间复杂度不同。

来看代码:

#!/bin/python

import sys

n = len(sys.argv) - 1
gaps = [72, 36, 24, 18, 12, 9, 8, 6, 4, 3, 2, 1]

for gap in gaps:
	for i in range(gap + 1, n + 1):
		j = i
		tmp = sys.argv[i]
		while(int(tmp, 10) < int(sys.argv[j - gap], 10)):
			sys.argv[j] = sys.argv[j - gap]
			j = j - gap
			if(j <= gap):
				break
		sys.argv[j] = tmp
		print sys.argv


根据gaps数组里面的数据可确定算法的时间复杂度,以下是来自wiki的一个表格:

(链接: http://en.wikipedia.org/wiki/Shellsort )

用以上的算法对数列[4, 2, 3, 10, 1, 7, 8, 21],过程如下:

['./shell.py', '4', '2', '3', '10', '1', '7', '8', '21']
['./shell.py', '4', '2', '3', '10', '1', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '10', '4', '7', '8', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '8', '4', '7', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '7', '4', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']
['./shell.py', '1', '2', '3', '4', '7', '8', '10', '21']


你可能感兴趣的:(算法,笔记,python,Python,ShellSort,shellsort,希尔排序,时间复杂度)