【发布时间】:2020-07-27 09:58:48
【问题描述】:
我有一个插入排序算法的实现,在讲座中,在 while 循环之前有一个新的实例变量。
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
def ins_sort(l):
for i in range(len(l)):
j = i
while j > 0 and l[j - 1] > l[j]:
swap(l, j - 1, j)
j = j - 1
return l
在我的测试中,算法在没有它的情况下也可以工作,我不明白为什么如果没有必要我需要编写额外的代码行。
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
def ins_sort(l):
for i in range(len(l)):
while i > 0 and l[i - 1] > l[i]:
swap(l, i - 1, i)
i = i - 1
return l
【问题讨论】:
-
临时值也不需要
swap函数。l[i], l[j] = l[j], l[i]也应该这样做 -
看来作者不懂Python。
标签: python insertion-sort