Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 关于插入排序实现输出的澄清_Python_Algorithm_Insertion Sort - Fatal编程技术网

Python 关于插入排序实现输出的澄清

Python 关于插入排序实现输出的澄清,python,algorithm,insertion-sort,Python,Algorithm,Insertion Sort,我希望能澄清Python中实现的插入排序算法。我使用以下伪代码作为指导来实现算法: 完全按照以下方式使用实现(将中的索引2替换为从0开始的python索引的循环): 正如您所见,它对列表中除零位值以外的所有值进行了排序 但是,如果我将while循环中的索引条件从I>0更改为I>=0,则列表在输出时顺序正确: l = [31, 41, 59, 26, 41, 58] for j in range(1, len(l)): key = l[j] i = j - 1 while

我希望能澄清Python中实现的插入排序算法。我使用以下伪代码作为指导来实现算法:

完全按照以下方式使用实现(将
中的索引
2
替换为从
0
开始的python索引的
循环):

正如您所见,它对列表中除零位值以外的所有值进行了排序

但是,如果我将while循环中的索引条件从
I>0
更改为
I>=0
,则列表在输出时顺序正确:

l = [31, 41, 59, 26, 41, 58]
for j in range(1, len(l)):
    key = l[j]
    i = j - 1
    while i >= 0 and l[i] > key:
        l[i+1] = l[i]
        i = i - 1
    l[i+1] = key


print(l)
>> [26, 31, 41, 41, 58, 59]

有人能解释一下为什么会这样吗?

您记得从索引中减去1,因为Python的列表在j
中是以零为基础的。当i>0时,您忘记在
中执行相同的操作。在i>0
时将
替换为
而i>=0
与在i>-1

时将
替换为
是一样的。谢谢你,你完全正确-我完全忽略了这一点,我感谢你简洁的回答。
l = [31, 41, 59, 26, 41, 58]
for j in range(1, len(l)):
    key = l[j]
    i = j - 1
    while i >= 0 and l[i] > key:
        l[i+1] = l[i]
        i = i - 1
    l[i+1] = key


print(l)
>> [26, 31, 41, 41, 58, 59]