Data structures and algorithms - sorting algorithm - insertion sort

 ################## insertion sort ####################

"""

Insertion algorithm:
alist = [54,26,93,17,77,31,44,55,20]
The sequence is divided into two parts,
Start off a first number that is ordered, alist = [54, 26,93,17,77,31,44,55,20]
The first round, the first and the last part of the second portion of the comparison, if it is a small exchange, alist = [26,54 93,17,77,31,44,55,20]
Second round, the first and last for a comparison of the first portion, a second portion smaller exchanged, and then forward, and if needed a small exchange,
So the total is to achieve after the first, and has been comparing the front from the back, knowing the end,

Select sort and insertion sort comparison:
Insertion sort is extracted from a second part, the first part from start to finish, and then to compare, and then inserted into,
And selecting a different sort, selection sort is divided into two parts, but it is behind the comparison, comparing it to a minimum and then inserted to the rearmost portion of the first, which is selection sort,

"""

 

 

################## insertion sort ####################

# First Edition:
def insert_sort(alist):
    n = len (alist)
    for j in range(1,n):
        i = j
        while i>0:
            if alist[i] < alist[i-1]:
                alist[i],alist[i-1]= alist[i-1],alist[i]
                i -=1
            else:
                break # without this one can, but can optimize the optimal time complexity for orderly queue, the complexity of the inner layer becomes 1, and


# second edition:
def insert_sort2(alist):
    # From the second position, i.e., the elements labeled 1 start to be inserted forwardly
    for i in range(1, len(alist)):
        Comparison # i th element of from the start of forward, is less than the previous element, the exchange position
        for j in range(i, 0, -1):
            if alist[j] < alist[j-1]:
                alist[j], alist[j-1] = alist[j-1], alist[j]

# The outer loop is to ensure that all elements are taken out of the second portion
# Inner loop is to ensure that the value taken out from the back comparison again, if small exchanged,


if __name__ == '__main__':

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

 

Guess you like

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