合并排序的Python实现 有什么问题?

2024-04-25 01:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

[在此处输入图像描述][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)  

Tags: 代码https图像ifstackdeftemplow
1条回答
网友
1楼 · 发布于 2024-04-25 01:50:33

总的来说,有两个问题:n=len(a)导致IndexError(分别更改为n=len(a)-1),并且您忘记了从temp复制到原始数组(将下面的代码这样的smth添加到combine例程的末尾:

for t in range(low, high+1):
    a[t] = temp[t]

相关问题 更多 >