【发布时间】:2018-05-09 06:02:55
【问题描述】:
我正在尝试实现归并排序。我有一个适用于排序列表的工作合并子功能,只需要正确管理所有列表的合并。
def mergesort(alist):
alist = [[i] for i in alist]
def merge(clist, dlist): #assume inputs are sorted
merged = []
while True:
if len(clist) == 0:
return merged + dlist
elif len(dlist) == 0:
return merged + clist
elif clist[0] < dlist[0]:
merged.append(clist[0])
del clist[0]
elif clist[0] > dlist[0]:
merged.append(dlist[0])
del dlist[0]
return merged
while True:
if len(alist) % 2 == 0 and len(alist) > 2:
alist = [merge(alist[2*i], alist[2 * i + 1]) for i in range(int(len(alist)/2))]
elif len(alist) == 2:
print('ayyy')
alist = merge(alist[0], alist[-1])
return alist
elif len(alist) % 2 == 1 and len(alist) > 1:
tag = alist[-1]
del alist[-1]
alist = [merge(alist[2 * i], alist[2 * i + 1]) for i in range(int(len(alist)/2))]
alist.append(tag)
else:
return alist
print(mergesort([10, 5, 8, 16, 258, 11, 1, 20, 489, 10, 5, 3, 12]))
该函数工作正常,直到它下降到最后两个列表。它打印“ayyy”,这意味着它进入了第一个 elif 语句,然后什么都不做。该程序不会终止,它只是旋转它的轮子。调试器显示alist 的值也没有更新。
【问题讨论】:
-
你有相同的元素(5 & 5)。内部合并函数无法处理它们,因此永远循环。