• python 插入排序


    插入排序:

    每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕

    先进行第一步:

    这一步是实现第一个待排序数字插到已经排好顺序的地方去

    def insert(lst, index):
        """
        列表lst从索引0到索引index-1 都是有序的
        函数将索引index位置上的元素插入到前面的一个合适的位置
        :param lst:
        :param index:
        :return:
        """
        if lst[index-1] < lst[index]:
            return
    
        tmp = lst[index]
        tmp_index = index
        while tmp_index > 0 and lst[tmp_index-1] > tmp:
            lst[tmp_index] = lst[tmp_index-1]
            tmp_index -= 1
        lst[tmp_index] = tmp
    
    
    if __name__ == '__main__':
        lst = [1, 2, 6, 7, 5,4]
        insert(lst, 4)
        print(lst)
        
    #[1, 2, 5, 6, 7, 4]

    第二步是利用调用函数,重复整个过程

    def insert(lst, index):
        """
        列表lst从索引0到索引index-1 都是有序的
        函数将索引index位置上的元素插入到前面的一个合适的位置
        :param lst:
        :param index:
        :return:
        """
        if lst[index-1] < lst[index]:
            return
    
        tmp = lst[index]
        tmp_index = index
        while tmp_index > 0 and lst[tmp_index-1] > tmp:
            lst[tmp_index] = lst[tmp_index-1]
            tmp_index -= 1
        lst[tmp_index] = tmp
    
    
    def insert_sort(lst):
        for i in range(1, len(lst)):
            insert(lst, i)
    
    
    if __name__ == '__main__':
        lst = [1, 6, 2, 7, 5,4,6]
        insert_sort(lst)
        print(lst)

    第1个元素单独看做一个数列,它本身就是有序的,那么只需要执行insert(lst, 1),就可以保证前两个数据变成有序的,然后执行insert(lst, 2),此时,从索引0到索引1是有需的,只需要将索引为2的数据插入到合适的位置就可以了

  • 相关阅读:
    Sybase自增字段跳号的解决方法
    sybase从表A创建表B
    timed out waiting for input: auto-logout
    关闭归档提示:ORA-38774: cannot disable media recovery
    vmware下给linux添加硬盘
    oracle 双机热备,oracle dataguard 和oracle rac的区别和联系(转)
    with admin option 与with grant option
    Python yield 使用浅析
    支持向量机的优缺点
    PCA MATLAB
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/13447051.html
Copyright © 2020-2023  润新知