Implementation of Python insertion sort

time complexity:

Optimal time complexity: O(n) (arranged in ascending order, the sequence is already in ascending order) 
worst time complexity: O(n^2) 
stability: stable

Ideas:

Compare each element with the previously sorted elements one by one, and when the element is larger than a certain sorted element, it will be placed behind it

To put it another way: start from the second element and compare it with the first element, and then compare the third element with the first two sorted elements one by one and enter the insertion at the back

Code

def insert_sort(ary):
    """
    插入排序:
    将每一个元素与前面已经排序的元素一一比较,当元素比某一个已经排序的元素大时就放在其后面
    """
    n = len(ary)
    for i in range(1, n):
        key = i - 1
        mark = ary[i]    # 注: 必须将ary[i]赋值为mark,不能直接用ary[i],目的是将这个数保存起来
        while key >= 0 and ary[key] > mark:
            ary[key+1] = ary[key]  # # 前面的数大于后面的数时就将后面的数替换为前面的数
            key -= 1  # 减1继续循环往前与之前保存的mark的值对比
        ary[key+1] = mark  # 当key不满足>=0时说明在循环里已经将所有的值都比较了一遍并替换了,这时将保存的mark值替换到第一个位置
    return ary


res = insert_sort(array)  # 插入排序
print(res)

Output result:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Guess you like

Origin blog.csdn.net/qq_37140721/article/details/130317371