简体   繁体   English

合并排序中的列表索引超出范围错误 function

[英]List index out of range error in merge sort function

I Wrote the program of Merge sort and while copying arrays i am getting error of list index out of range while assigning values to new array at L[i] = A[p+i]我编写了合并排序程序,在复制 arrays 时,在L[i] = A[p+i]处为新数组分配值时出现列表索引超出范围的错误

A = [1,2,6,8,3,4,5,7]
# p = 0,r = 7 ,q = 3
def Merge(A,p,q,r):
    n1 = q - p
    n2 = r - q
    L = []
    R = []
    for i in range(n1):
        L[i] = A[p+i]
    for i in range(n2):
        R[i] = A[q+i]
    i = 0
    j = 0
    Array = []
    for x in range(p,r):
        if L[i] < R[j]:
            Array[x] = L[i]
            i = i +1
        else:
            Array[x] = R[j]
            j = j +1
Merge(A,0,3,7)

Your L and R arrays are empty and you try to access L[i] and R[i] in the for loop.您的 L 和 R arrays 为空,您尝试在 for 循环中访问 L[i] 和 R[i]。 This leads to the index error.这会导致索引错误。 Try to initialize the array first to access its index.尝试先初始化数组以访问其索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM