Data Structures and Algorithms - sorting algorithms - Shell sort

 ################## Hill sorting ####################### #

"" " 

Shell sort 
Shell sort is an improved version of insertion sort, 

steps of the algorithm 
to a sequence is not as a whole, but as a plurality of sequences, 
assumption of constant intervals. 4 is = GAP 
alist = [54,26 , 93,17,77,31,44,55,20] 
54,26,93,17,77,31,44,55,20 
547 720 which is a group interval is 4, 
   2631 which is a set of 2 , the spacer 4, 
      9344 which is a group 3, 4 is a spacer, 
         1755 which is a group 4, 4 is a spacer, 

and each group is inserted sorting algorithm, 
[547,720], is that the first 54 and comparing each to the front and the back, insertion, -------- [205,477] 

are all sorted after the completion, again combined into one sequence, 
and then change the interval, such as a gap = 2, again insertion sorting algorithm, 

then again be merged as a whole or sequence 
adjustment again gap, such gap = 1, and then sorted again until the sorting is completed, 



"" "

 

 

 

################## Hill sorting ####################### #

# First Edition: 
DEF shell_sort (alist): 
    n-= len (alist) 
    gap = n-2 // 
    the while gap> 0: 
        # The outermost control loop is a gap, smaller, 
        for J in Range ( GAP, n-): 
            I = J 
            the while I> 0: 
                IF alist [I] <alist [I - GAP]: 
                    alist [I], alist [I - GAP] = alist [I - GAP], alist [I] 
                    I - = gap 
                the else: 
                    BREAK 
        # shorten the gap step, 
        gap = 2 // 

# second Edition: 
DEF shell_sort2 (alist): 
    n-= len (alist) 
    # initial step 
    gap = n-2 // 
    the while gap> 0: 
        # insertion sort step 
        for i in range (gap, n) :
            J = I 
            # insertion sort 
            the while J> = GAP and alist [J-GAP]> alist [J]: 
                alist [J-GAP], alist [J] = alist [J], alist [J-GAP] 
                J - = GAP 
        # get the new step size 
        GAP = GAP / 2 

IF the __name__ == '__main__': 

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

 

Guess you like

Origin www.cnblogs.com/andy0816/p/12348381.html