首页 > 编程语言 > 详细

插入排序——Python实现

时间:2019-10-28 23:13:02      阅读:63      评论:0      收藏:0      [点我收藏+]

插入排序Python实现

# -*- coding: utf-8 -*-
# @Time    : 2019/10/28 20:47
# @Author  : yuzhou_1shu
# @Email   : yuzhou_1shu@163.com
# @File    : insertion_sort.py
# @Software: PyCharm

def insertion_sort(collection):
    """Python实现插入排序算法
    将插入排序模拟成抓扑克牌:
    1、当抓到第一个牌肯定是有序的
    2、然后抓到第二张牌,如果比第一张大,放在右边;如果小,放在第一张左边;相等,左右都可以
    :param collection: 待排序序列
    :return: 升序排好的对应序列
    """

    length = len(collection)
    # 第一张牌肯定有序,所以循环变量从1开始(也就是第二张牌开始插入),i代表摸到的牌
    for i in range(1, length):
        insertion_index = i
        while(insertion_index > 0 and collection[insertion_index - 1] > collection[insertion_index]):
            collection[insertion_index], collection[insertion_index-1] = (collection[insertion_index-1], collection[insertion_index])
            insertion_index -= 1

    return collection


if __name__ == "__main__":

    list1 = [5, 5, 1, 4, 1, 2, 3]
    print("排序前: ", list1)
    print("排序后: ", insertion_sort(list1))

插入排序——Python实现

原文:https://www.cnblogs.com/yuzhou-1su/p/11755600.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!