Python插入排序(1)

Python代码: 

"""
插入排序(1)

将未排序的数逐个插入到已排序的数组中

"""

lst = [3, 6, 9, 1, 4, 7, 2, 8, 5, 0]
print("排序前: %s\r\n" %lst)

#
for i in range(1,len(lst)): # 未排序的数组
    print("第%s轮" % i)
    #
    for j in range(i): # 已排序的数组(初始假设第一个数已排序)
        if lst[i] <= lst[j]:
            print("    比较[%s]:%s [%s]:%s,需插入" %(i, lst[i], j, lst[j]))
            lst.insert(j, lst[i])
            lst.pop(i+1)
            print("    插入后: %s" %lst)
            break
        else:
            print("    比较[%s]:%s [%s]:%s,不插入" %(i, lst[i], j, lst[j]))

print("\r\n排序后:  %s" % lst)

 

输出结果:

E:\python\algorithm>python3 insertSort.py
排序前: [3, 6, 9, 1, 4, 7, 2, 8, 5, 0]

第1轮
    比较[1]:6 [0]:3,不插入
第2轮
    比较[2]:9 [0]:3,不插入
    比较[2]:9 [1]:6,不插入
第3轮
    比较[3]:1 [0]:3,需插入
    插入后: [1, 3, 6, 9, 4, 7, 2, 8, 5, 0]
第4轮
    比较[4]:4 [0]:1,不插入
    比较[4]:4 [1]:3,不插入
    比较[4]:4 [2]:6,需插入
    插入后: [1, 3, 4, 6, 9, 7, 2, 8, 5, 0]
第5轮
    比较[5]:7 [0]:1,不插入
    比较[5]:7 [1]:3,不插入
    比较[5]:7 [2]:4,不插入
    比较[5]:7 [3]:6,不插入
    比较[5]:7 [4]:9,需插入
    插入后: [1, 3, 4, 6, 7, 9, 2, 8, 5, 0]
第6轮
    比较[6]:2 [0]:1,不插入
    比较[6]:2 [1]:3,需插入
    插入后: [1, 2, 3, 4, 6, 7, 9, 8, 5, 0]
第7轮
    比较[7]:8 [0]:1,不插入
    比较[7]:8 [1]:2,不插入
    比较[7]:8 [2]:3,不插入
    比较[7]:8 [3]:4,不插入
    比较[7]:8 [4]:6,不插入
    比较[7]:8 [5]:7,不插入
    比较[7]:8 [6]:9,需插入
    插入后: [1, 2, 3, 4, 6, 7, 8, 9, 5, 0]
第8轮
    比较[8]:5 [0]:1,不插入
    比较[8]:5 [1]:2,不插入
    比较[8]:5 [2]:3,不插入
    比较[8]:5 [3]:4,不插入
    比较[8]:5 [4]:6,需插入
    插入后: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
第9轮
    比较[9]:0 [0]:1,需插入
    插入后: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

排序后:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

=====结束=====

posted @ 2018-01-26 16:01  sam11  阅读(152)  评论(0编辑  收藏  举报