插入排序——Python實現

插入排序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實現插入排序算法
    將插入排序模擬成抓撲克牌:
    一、當抓到第一個牌確定是有序的
    二、而後抓到第二張牌,若是比第一張大,放在右邊;若是小,放在第一張左邊;相等,左右均可以
    :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))
相關文章
相關標籤/搜索