【发布时间】:2015-12-09 11:40:05
【问题描述】:
我正在努力理解和实现合并排序。我在这方面遇到了一堵砖墙,似乎无法获得有效的实现。我当前的实现遇到了“列表索引超出范围”错误。这是我的代码:
def merge_sort(list_a):
mid = len(list_a) // 2
print('Mid is ', mid)
while len(list_a) > 1:
left = list_a[:mid]
print('Left is now ', left)
right = list_a[mid:]
print('Right is now ', right)
merge_sort(left)
merge_sort(right)
merge(list_a, left, right)
def merge(comb_list, list_a, list_b):
print('Starting the merge.')
a1, b1, c1 = 0, 0, 0
na, nb, nc = len(list_a), len(list_b), len(comb_list)
while a1 < na and b1 < nb:
if list_a[a1] < list_b[b1]:
print('Adding from A')
comb_list[c1] = list_a[a1]
a1 += 1
else:
print('Adding from B')
comb_list[c1] = list_b[b1]
b1 += 1
c1 += 1
while list_a:
comb_list[c1] = list_a[a1]
c1 += 1
a1 += 1
while list_b:
comb_list[c1] = list_b[b1]
c1 += 1
b1 += 1
if __name__ == '__main__':
list_a = [54,26,93,17,77,31,44,55,20]
merge_sort(list_a)
【问题讨论】:
-
while list_a:表示while len(list_a) != 0:。您不会在 while 块内修改您的list_a,因此这个循环是无休止的,变量a1会增长并超出列表长度。