List index out of range error in merge sort function

Viewed 20

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]

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)
1 Answers

Your L and R arrays are empty and you try to access L[i] and R[i] in the for loop. This leads to the index error. Try to initialize the array first to access its index.

Related