[在此处输入图像描述][1]
[1]:https://i.stack.imgur.com/JNtR5.pngstrong文本
此代码工作不正常。这个代码怎么了?怎么能修好呢?
a=[2,5,8,7,1,9,6]
n=len(a)
temp=[0]*(n+1)
def mergesort(a,low,high):
if low < high:
mid=(low+high)/2
mergesort(a,low,mid)
mergesort(a,mid+1,high)
combine(a,low,mid,high)
print(a)
def combine(a,low,mid,high):
k=low
i=low
j=mid+1
while i<=mid and j<=high:
if a[i]<=a[j]:
temp[k]=a[i]
k=k+1
i=i+1
else:
temp[k]=a[j]
k+=1
j+=1
while i<=mid:
temp[k]=a[i]
i+=1
k+=1
while j<=high:
temp[k]=a[j]
j+=1
k+=1
print('lets sort the array')
mergesort(a,0,n)
总的来说,有两个问题:
n=len(a)
导致IndexError(分别更改为n=len(a)-1
),并且您忘记了从temp复制到原始数组(将下面的代码这样的smth添加到combine
例程的末尾:相关问题 更多 >
编程相关推荐