简体   繁体   English

在python中插入排序?

[英]insertion sort in python?

I wrote a code for insertion sort that now works great (yes, it's homework). 我写了一个插入排序代码,现在很好用了(是的,这是家庭作业)。 But, before that code I wrote a different one that doesn't work and I just don't know why. 但是,在编写该代码之前,我编写了另一种无效的代码,而我只是不知道为什么。 Please help me understand... 请帮助我理解...

This is my older code: 这是我的旧代码:

def insertion_sort(lst):
    if len(lst)==1:
        lst=lst
    else:
        for i in lst[1:]:
            if i==min(lst[0:lst.index(i)]):
                 lst.remove(i)
                 lst.insert(0, i)
    return lst

I do not need a new insertion sort, I already wrote one. 我不需要新的插入排序,我已经写了一个。 I just need the explanation for why this specific code didn't work. 我只需要解释为什么此特定代码不起作用。

The problem is that sometimes, even though i isn't the smallest of lst[0:lst.index(i)] , it still needs to be moved downwards. 问题是,即使i不是lst[0:lst.index(i)]的最小个,它仍然需要向下移动。 So, for example, if lst[0:lst.index(i)] is [0, 1, 2, 4, 3] , then even though the minimum is 0 , you still need to move 3 down a place for insertion sort to work. 因此,例如,如果lst[0:lst.index(i)][0, 1, 2, 4, 3] lst[0:lst.index(i)] [0, 1, 2, 4, 3] ,那么即使最小值为0 ,您仍然需要将3向下移动一个位置才能进行插入排序上班。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM