我写了这个插入排序,但由于某种原因它没有返回任何东西,我无法弄清楚原因。有人可以看一下吗?
def insertionSort(lis):
for i in range (1, len(lis)):
j = i - 1
value = lis[i]
while j >= 0:
if value < lis[j]: #have to be value because the number has to remain the same
lis[j+1] = lis[j]
j-= 1
else:
lis[j+1] = value
return lis
答案 0 :(得分:3)
你有一个无限循环。 在这段代码中:
while j >= 0:
if value < lis[j]: #have to be value because the number has to remain the same
lis[j+1] = lis[j]
j-= 1
else:
lis[j+1] = value
一旦到达value < lis[j]
为假的点,j
就不会减少,while
循环将永远不会退出。
如果你愿意的话,我可以为你写一个正确的插入排序,但我认为这会破坏你自己试图做到这一点。
答案 1 :(得分:-1)
请查看此示例代码,它可能对您有所帮助
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)