python实现插入法排序算法

2022-03-11 00:00:00 算法 排序 插入

python实现插入法排序算法,本文使用两种不同的写法实现了插入法排序

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/21
功能描述:python实现插入法排序算法
"""

# 方法1
def insertsort1(array):
    for removed_index in range(1, len(array)):
        removed_value = array[removed_index]
        insert_index = removed_index
        while insert_index > 0 and array[insert_index - 1] > removed_value:
            array[insert_index] = array[insert_index - 1]
            insert_index -= 1
        array[insert_index] = removed_value
        return array

# 方法2
def insertsort2(array):
    for lastsortedelement in range(len(array) - 1):
        checked = lastsortedelement
        while array[checked] > array[lastsortedelement + 1] and checked >= 0:
            checked -= 1
        # Insert the number into the correct position
        array[checked + 1], array[checked + 2: lastsortedelement + 2] = array[lastsortedelement + 1], array[checked + 1: lastsortedelement + 1]
    return array

print(insertsort1([19, 42, 33, 43, 58, 60, 43, 62, 73, 54, 523]))
print(insertsort2([19, 42, 33, 43, 58, 60, 43, 62, 73, 54, 523]))

输出结果:
[19, 42, 33, 43, 58, 60, 43, 62, 73, 54, 523]
[19, 33, 42, 43, 43, 54, 58, 60, 62, 73, 523]

以上代码在python3.9环境下测试通过

相关文章