Sort sorting algorithm ---- Hill

Shell sort

  Hill sorting (Shell Sort) is an insertion sort. Also called incremental reduction sort, is inserted directly into a more efficient algorithm for Priority improved version, the basic idea of ​​the method is: the entire first element of the sequence to be divided into several sub-sequences (separated by a row of a "delta (gap time) "composed of elements) were sorted directly into, and then followed by reducing the incremental sort, to be substantially the entire ordered sequence of elements (increments small enough), then all elements of a direct insertion sort. Because direct insertion sort order in the case of basic elements (close to the best case), the efficiency is very high, so at time Hill sorting efficiency greatly higher than direct insertion sort.  

  

  

 1 """
 2 希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。
 3 """
 4 
 5 
 6 # 方式一:元素采取直接插入排序从前往后比较
 7 def shell_sort(int_list):
 8     length = len(int_list)
 9     if length <= 1: return int_list
10     step = length // 2
11 
12     while step > 0:
13         for i in range(step, length, step):
14             item = int_list[i]
15             for j in range(0, i, step):
16                 if int_list[j] > item:
17                     for k in range(i, j, -step):
18                         int_list[k] = int_list[k - step]
19                     int_list[j] = item
20                     break
21         step //= 2
22     return int_list
23 
24 
25 # 方式二:元素采取直接插入排序从后往前比较
26 # 继续缩小增量
27 def shell_sort1(alist):
28     gap = len(alist) // 2
29     while gap >= 1:
30         # 将增量设置成gap
31         for i in range(gap, len(alist)):
32             while i > 0:
33                 if alist[i] < alist[i - gap]:
34                     alist[i], alist[i - gap] = alist[i - gap], alist[i]
35                     i -= gap
36                 else:
37                     break
38         gap //= 2
39     return alist
40 
41 
42 # print(shell_sort([11, 3, 5, 89, 1,23456,87678,2345,4567,0,3,5]))
43 if __name__ == '__main__':
44     int_str = input("请输入逗号分割的整数>>>").strip()
45     int_list = [int(i) for i in int_str.split(",")]
46     print(shell_sort(int_list))
47     # print(shell_sort1(int_list))

 

Guess you like

Origin www.cnblogs.com/open-yang/p/11367089.html