这是我用于合并排序的 Python 代码,我不明白为什么我得到了IndexError
第 23 行。
如果将第 23 行放在for
循环之前但在for
循环中它说list index out of range
. :(
from math import floor
def merge_sort(a,p,r):
if p < r:
q = (p+r)/2
merge_sort(a,p,q)
merge_sort(a,q+1,r)
merge(a,p,q,r)
def merge(A,p,q,r):
n1 = q - r +1
n2 = r - q
L = []
R = []
#print n1
for i in range (1,n1):
L.append(a[p+i-1])
for j in range (1,n2):
R.append(a[q+j])
L.append(10000)
R.append(10000)
i,j=0,0
for k in range (p,r):
if L[i] <= R [j]: # This is where the error occurs
A[k] = L[i]
i = i + 1
else :
A[k] = R[j]
j = j + 1
a=[1,4,9,8,2,3,8,2,9]
merge_sort(a,1,len(a))
print a