为什么我的合并排序代码给出索引错误

时间:2020-02-17 08:40:00

标签: python

我已经按照Cormen在“算法介绍”中给出的伪代码编写了用于合并排序的代码,但是在运行代码时,我遇到了很长的追溯错误,随后出现列表分配索引的索引错误,超出范围。 代码如下:

def merge(a, p, q, r):
    n = q-p+1
    m = r-q
    b = [0]*(n)
    c = [0]*(m)
    for i in range(0, n):
        b[i] = a[p+i]
    for j in range(0, m):
        c[i] = a[q+1+j]
    b[n+1] = math.inf
    c[m+1] = math.inf
    i = 0
    j = 0

    for k in range(p, r+1):
        if b[i] < c[j]:
            a[k] = b[i]
            i += 1
        else:
            a[k] = c[j]
            j += 1


def mergesort(a, p, r):
    if p < r:
        q = (p+r)//2
        mergesort(a, p, q)
        mergesort(a, q+1, r)
        merge(a, p, q, r)


a = [4, 0, 6, 1, 5, 2, 3]
n = len(a)
print(*a, sep=" ")
mergesort(a, 0, n-1)
for i in range(0, n):
    print("the  sorted array is", a[i])

代码给出以下回溯错误:

  File "m.py", line 38, in <module>
    mergesort(a, 0, n-1)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 30, in mergesort
    mergesort(a, p, q)
  File "m.py", line 32, in mergesort
    merge(a, p, q, r)
  File "m.py", line 13, in merge
    b[n+1] = math.inf
IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:0)

代替

    b[n+1] = math.inf
    c[m+1] = math.inf

使用

    b.append(math.inf)
    c.append(math.inf)