python实现插入法排序算法的代码

本文提供了两种使用Python实现的插入排序算法。第一种方法通过遍历数组并调整元素位置来完成排序;第二种方法同样实现了排序功能,并将待排序的元素放置到正确的位置。这两种方法为程序员提供了实现插入排序的有效途径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将开发过程中比较常用的内容做个记录,下面内容内容是关于python实现插入法排序算法的内容,应该对码农们有一些用。

def insertsort(array):
for removed_index in range(1, len(array)):
removed_value = array[removed_index]
insert_index = removed_index
while insert_index > 0 and array[insert_index - 1] > removed_value:
array[insert_index] = array[insert_index - 1]
insert_index -= 1
array[insert_index] = removed_value

另外一个版本

def insertsort(array):
for lastsortedelement in range(len(array)-1):
checked = lastsortedelement
while array[checked] > array[lastsortedelement + 1] and checked >= 0:
checked -= 1
#Insert the number into the correct position
array[checked+1], array[checked+2 : lastsortedelement+2] = array[lastsortedelement+1], array[checked+1 : lastsortedelement+1]
return array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值