【发布时间】:2014-09-13 15:18:09
【问题描述】:
我有一个使用 Python 的家庭作业,但我遇到了大脑冻结。所以我应该使用插入排序来做 O(nˇ2) 练习。 例如,我有两个列表 [] 和 [5,8,1,1] 并且程序应该通过从第一个列表中删除并以正确的顺序将值从一个列表插入另一个列表: [][5,8,1,1] = [5][8,1,1] = [5,8][1,1] = [1,5,8][1] = [1,1, 5,8][]
我想出了一些办法,不知道我是否走在正确的轨道上,但这似乎是最合理的。缩进是有序的,但是在这里复制代码会以某种方式搞砸了。 P.S 对不起爱沙尼亚语,必须用爱沙尼亚语编写代码。
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。
【问题讨论】:
标签: python insertion-sort