Python data structure and algorithm----Hill sort

Hill sort

Shell Sort is a type of insertion sort. Also known as shrinking incremental sort, it is a more efficient and improved version of the direct insertion sort algorithm. Hill sort is an unstable sorting algorithm. This method is due to DL. Shell was named after it was proposed in 1959. Hill sorting is to group the records by a certain increment of the subscript, and use the direct insertion sorting algorithm to sort each group; as the increment gradually decreases, each group contains more and more keywords. When the increment is reduced to 1, The entire file is just grouped together, and the algorithm terminates.

Hill sort process

The basic idea of ​​Hill sort is: list the arrays in a table and insert the columns separately, repeat this process, but use longer columns each time (the step size is longer, the number of columns is less) to perform . Finally, the entire table has only one column. Converting the array to a table is to better understand the algorithm, which itself uses the array for sorting.

For example, given a set of numbers [ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ], if we start sorting with a step size of 5, we can Tables to better describe the algorithms, so they should look like this (the vertical elements are the steps):

13 14 94 33 82
25 59 94 65 23
45 27 73 25 39
10

Then we sort each column:

10 14 73 25 23
13 27 94 33 39
25 59 94 65 82
45

When the above four lines of numbers are joined together in sequence, we get: [ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ]. At this point 10 has been moved to the correct position, and then sorted in steps of 3:

10 14 73
25 23 13
27 94 33
39 25 59
94 65 82
45

After sorting it becomes:

10 14 13
25 23 33
27 25 59
39 65 73
45 94 82
94

Finally, sort by 1 step (this is a simple insertion sort)

Analysis of Hill Sort

def shell_sort(alist):
    n = len (alist)
    gap=4
    while gap>=1: #When the gap is equal to 1, it is insertion sort
        # Insertion sort by step size
        for j in range(gap,n):
            i=j
            # Insertion sort for each small group
            while i>0:
                if alist[i]<alist[i-gap]:
                    alist[i],alist[i-gap]=alist[i-gap],alist[i]
                    i-=gap
                else:
                    break
        gap//=2

alist = [54,226,93,17,77,31,44,55,44,20]
shell_sort(alist)
print(alist)

time complexity

  • Optimal time complexity: varies according to the sequence of steps
  • Worst time complexity: O(n 2 )
  • Stable thought: unstable

Hill Sort Demo


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325652169&siteId=291194637