繁体   English   中英

Python中的插入排序

[英]Insertion sort in Python

我在Python中做了一个家庭作业,并且遇到了大脑冻结。 所以我应该使用插入排序进行O(n2)练习。 例如,我有两个列表[]和[5,8,1,1],程序应该从一个列表中插入值到另一个列表,从第一个和正确的顺序删除到另一个:[] [5,8,1, 1] = [5] [8,1,1] = [5,8] [1,1] = [1,5,8] [1] = [1,1,5,8] []

我想出了一些东西,不知道我是否正确,但这似乎是最合理的。 缩进是有序的,但复制代码在这里以某种方式搞砸了它。 PS对不起爱沙尼亚语,必须用爱沙尼亚语编写代码。

def pisteMeetod2(t2ishulk):
    tulemus = [] #new list
    hulgacopy = t2ishulk[0:len(t2ishulk)] #main list
    for el in t2ishulk: #going through first list
        if not tulemus: #if list empty (which it at the beginning is) then from here
            tulemus.append(el)
            del hulgacopy[0]
        else:
            for elemendid in tulemus: #check if there is a lower element from new list
                n = 0
                if hulgacopy[0] <= tulemus[n]:
                    tulemus.insert(n-1,el)
                    del hulgacopy[0]
                    break
                n = n + 1

所以现在我遇到麻烦,第二次循环怎么办。 在检查了名为“tulemus”的结果列表中的元素之后,如果找不到任何匹配,我应该如何继续我的代码,以便将“el”附加到tulemus中。

您可以在内部for循环中添加else子句:

for elemendid in tulemus: #check if there is a lower element from new list
    n = 0
    if hulgacopy[0] <= tulemus[n]:
        tulemus.insert(n, el)
        del hulgacopy[0]
        break
    n = n + 1
else:
    tulemus.append(el)
    del hulgacopy[0]

如果循环未使用break终止,则会执行其正文。 您可以在Python的官方教程中阅读有关循环上的else子句的更多信息。

另请注意,如果在迭代时找到插入点,则应使用tulemus.insert(n, el)而不是tulemus.insert(n-1, el)将当前元素插入其中。 否则,当n == 0时,您将最终插入列表的末尾(索引-1)。

暂无
暂无

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

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