首页 > 编程语言 > 详细

插入排序(使用Python描述)

时间:2020-03-14 20:59:59      阅读:73      评论:0      收藏:0      [点我收藏+]

问题描述

?? 如果觉得不容易理解请查看底部的算法可视化



代码描述

# 插入算法
def insertion_sort(arr):
    for i in range(1,len(arr)): # 默认将第一个元素设置为已排序.

        current = arr[i] # 当前需要主动与遍历元素要进行对比的值
        pre_index = i-1 # 往前一步

        while pre_index >=0 and arr[pre_index] > current: # 限制条件:下标>=0 且前一个元素大于当前元素
            
            arr[pre_index+1] = arr[pre_index] # 将元素往后面赋值一位.
            pre_index -= 1
        arr[pre_index+1] = current # 跳出循环条件.插入元素

    return arr

# insertion_sort([11,33, 36, 39, 44, 55, 66, 69, 77, 88, 99,11, 22, 33, ])
print(insertion_sort([33,22,11]))




参考

插入排序(使用Python描述)

原文:https://www.cnblogs.com/gtscool/p/12493685.html

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