简体   繁体   English

Python 就地合并排序错误:索引超出范围

[英]Python in-place merge sort error: index out of range

would anyone know why my in place merge sort is "index out of range" ?有谁知道为什么我的就地合并排序是“索引超出范围”

I originally had my "low" at 0 but decided to do a +1 for each "low,mid,high" to compensate for index space.我最初的“低”为 0,但决定为每个“低、中、高”做一个 +1 以补偿索引空间。 Can anyone find anything?任何人都可以找到任何东西吗? Thanks.谢谢。

def merge(array, low, mid, high):

    i,j,k = low,mid+1,low
    leftarray = array[low:mid+1]
    rightarray = array[mid+1:high+1]

    temp= [0]*high

    while i<=mid and j<=high:

        if array[i]<array[j]:
            temp[k] = array[i]
            i+=1
        else:
            temp[k] = array[j]
            j+=1
        k+=1

    if i>mid:
        temp[k:high+1] = array[j:high+1]
    else:
        temp[k:high+1] = array[i:mid+1]  

    array[low:high+1] = temp[low:high+1]

    def inplace(array,low,high):

        if low<high:
            mid = int((low+high)/2)
            inplace(array,low,mid)
            inplace(array,mid+1,high)
            merge_test(array,low,mid,high)


    array = [20,30,21,15,42,45,31,0,9]
    inplace(array, 0, len(array)-1)
    print(array)
  • The error you have is in your code this part is incorrectly indented.您遇到的错误是在您的代码中,这部分的缩进不正确。 It should be outside of while loop.它应该在while循环之外。 Once merging is done.一旦合并完成。 Refer to merge sort pseudo code to find where is the bug.请参阅合并排序伪代码以查找错误所在。
if i>mid:
    temp[k:high+1] = array[j:high+1]
else:
    temp[k:high+1] = array[i:mid+1]  

array[low:high+1] = temp[low:high+1]
  • The following code is working.以下代码正在运行。
def merge_test(array, low, mid, high):

    i,j,k = low,mid+1,low
    leftarray = array[low:mid+1]
    rightarray = array[mid+1:high+1]

    temp= [0]*high

    while i<=mid and j<=high:

        if array[i]<array[j]:
            temp[k] = array[i]
            i+=1
        else:
            temp[k] = array[j]
            j+=1
        k+=1


    if i>mid:
        temp[k:high+1] = array[j:high+1]
    else:
        temp[k:high+1] = array[i:mid+1]  

    array[low:high+1] = temp[low:high+1]


def inplace(array,low,high):

    if low<high:
        mid = int((low+high)/2)
        inplace(array,low,mid)
        inplace(array,mid+1,high)
        merge_test(array,low,mid,high)


array = [20,30,21,15,42,45,31,0,9]
inplace(array, 0, len(array)-1)
print(array)

output : output

[0, 9, 15, 20, 21, 30, 31, 42, 45]

PS: please always post full error stack trace. PS:请始终发布完整的错误堆栈跟踪。 It helps debugging code.它有助于调试代码。 You should also try reading stack trace.您还应该尝试阅读堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM