希尔排序介绍
希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本,该方法的基本思想是:先将整个待排元素序列分割成若干个子序列(由相隔某个“增量”的元素组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序(增量足够小)时,再对全体元素进行一次直接插入排序。因为直接插入排序在元素基本有序的情况下(接近最好情况),效率是很高的,因此希尔排序在时间效率比直接插入排序有较大提高。
![这里写图片描述]()
-
首先要明确一下增量的取法:
-
第一次增量的取法为: d=count/2;
第二次增量的取法为: d=(count/2)/2;
最后一直到: d=1;
-
看上图观测的现象为:
-
d=3时:将40跟50比,因50大,不交换。
将20跟30比,因30大,不交换。
将80跟60比,因60小,交换。
d=2时:将40跟60比,不交换,拿60跟30比交换,此时交换后的30又比前面的40小,又要将40和30交换,如上图。
将20跟50比,不交换,继续将50跟80比,不交换。
d=1时:这时就是前面讲的插入排序了,不过此时的序列已经差不多有序了,所以给插入排序带来了很大的性能提高。
代码实例:
import time,random
source = [ random.randrange(10000+i) for i in range(10000)]
step = int(len(source)/2)
t_start = time.time()
while step >0:
print("---step ---", step)
for index in range(0,len(source)):
if index + step < len(source):
current_val = source[index]
if current_val > source[index+step]:
source[index], source[index+step] = source[index+step], source[index]
step = int(step/2)
else:
for index in range(1, len(source)):
current_val = source[index]
position = index
while position > 0 and source[
position - 1] > current_val:
source[position] = source[position - 1]
position -= 1
source[position] = current_val
print(source)
t_end = time.time() - t_start
print("cost:",t_end)