#merge function
def merge(A, p, q, r):
n1=q-p+1
n2=r-q;
L=[0]*(n1)
R=[0]*(n2)
for i in range(0,n1):
L[i]=A[p+i]
for j in range(0,n2):
R[j]=A[q+j+1]
L[i]=65000
R[j]=65000
i=0
j=0
for k in range(p,r+1):
if L[i]<R[j] :
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
#merge sort function
def mergesort(A,p,r):
if p<r:
q=(p+(r-1))/2
mergesort(A,p,q)
mergesort(A,q+1,r)
merge(A,p,q,r)
#calling mergesort
A=[5,4,3,2,1]
mergesort(A,0,len(A))
print(A)
我得到的错误:https://imgur.com/OAV2LbT
Traceback (most recent call last):
File "<folder>\mergesort.py", line 44, in <module>
mergesort(A,0,len(A)-1)
File "<folder>\mergesort.py", line 35, in mergesort
merge(A,p,q,r)
File "<folder>\mergesort.py", line 19, in merge
if L[i]<R[j] :
IndexError: list index out of range
答案 0 :(得分:-1)
for k in range(p,r+1):
由于您已将len(A)
作为r
的值传递,因此无需添加其他1
:
for k in range(p,r):